[R] Defining a floor value in a data.frame on a row-by-row basis

Uwe Ligges ligges at statistik.uni-dortmund.de
Fri Mar 16 10:31:02 CET 2007


* Feng, Ken [CIB-EQTY] <ken.feng at citigroup.com> [070316 09:40]:
> Hi,
> 
> I have a data frame x, and a vector y which limits x by rows
> so that no element of x in that row is smaller than y.
> 
> For example,
> 
> > x <- as.data.frame( t( array( 1:9, dim=c(3,3))))
> > y <- c( 2, 8, 0 )
> > x
>   V1 V2 V3
> 1  1  2  3
> 2  4  5  6
> 3  7  8  9
> > y
> [1] 2 8 0
> 
> =============================================
> I want to get this:
> 
>   V1 V2 V3
> 1  2  2  3
> 2  8  8  8
> 3  7  8  9
> 
> =============================================
> 
> I tried:
> 
> x[ x<=y ] <- y
> 
> but R wasn't happy.
> 
> I know I can do this with a loop, but there has to be a way which I can avoid it...

sapply(x, function(xc) ifelse(xc < y, y, xc))

Uwe Ligges

 
> Thanks in advance.
> 
> - Ken
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list