Feng, Ken [CIB-EQTY]
2007-Mar-16 08:37 UTC
[R] Defining a floor value in a data.frame on a row-by-row basis
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 ) > xV1 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... Thanks in advance. - Ken
Uwe Ligges
2007-Mar-16 09:31 UTC
[R] Defining a floor value in a data.frame on a row-by-row basis
* 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.