[R] referring to a row number and to a row condition, and to columns simultaneously

Dimitri Liakhovitski ld7631 at gmail.com
Fri Sep 18 00:18:15 CEST 2009


Thanks a lot for your great suggestions!
Dimitri

On Thu, Sep 17, 2009 at 5:48 PM, David Winsemius <dwinsemius at comcast.net> wrote:
>
> On Sep 17, 2009, at 5:17 PM, Dimitri Liakhovitski wrote:
>
>> 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
>
>
>
>  x$d[2:5] <- 8*(x$a[2:5] == 1) + 101*(x$a[2:5] != 1)
>  x$e[2:5] <- 9*(x$a[2:5] == 1) + 102*(x$a[2:5] != 1)
>
>> x
>  a b  c   d   e
> 1 4 1 NA  NA  NA
> 2 2 3  2 101 102
> 3 4 4  5 101 102
> 4 1 1  3   8   9
> 5 3 5  4 101 102
> 6 4 0 NA  NA  NA
>
>
>>
>> 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
>>
>> ______________________________________________
>> R-help at r-project.org 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.
>
> David Winsemius, MD
> Heritage Laboratories
> West Hartford, CT
>
>



-- 
Dimitri Liakhovitski
Ninah.com
Dimitri.Liakhovitski at ninah.com




More information about the R-help mailing list