[R] referring to a row number and to a row condition, and to columns simultaneously
Dimitri Liakhovitski
ld7631 at gmail.com
Thu Sep 17 23:17:08 CEST 2009
Hello, dear R-ers!
I have a data frame:
x<-data.frame(a=c(4,2,4,1,3,4),b=c(1,3,4,1,5,0),c=c(NA,2,5,3,4,NA),d=rep(NA,6),e=rep(NA,6))
x
When x$a==1, I would like to replace NAs in columns d and e with 8 and
9, respectively
When x$a != 1, I would like to replace NAs in columns d and e 101 and
1022, respectively.
However, I only want to do it for rows 2:5 - while ignoring what's
happening in rows 1 and 6.
Here is what I've come up with:
x
for(i in 2:5){
x[i & x[[1]]==1,4:5]<-c(8,9)
x[i & x[[1]]!=1,4:5]<-c(101,102)
}
x
However, something is wrong here.
First, rows 1 and 6 are not ignored.
Second, the order of 101 and 102 changes - I, however, always want to
see 101 in column d and 102 in column e.
Any advice?
Thanks a lot!
--
Dimitri Liakhovitski
Ninah.com
Dimitri.Liakhovitski at ninah.com
More information about the R-help
mailing list