[R] add an idx column to the matrix
Lida Zeighami
lid.zigh at gmail.com
Wed Aug 12 20:04:16 CEST 2015
I applied this code in a loop function but since in some matrices there
isn't any 2, so I got the below error:
idx<- apply(lofGT_met,1, function(x)as.numeric(any(x==2 & !is.na(x))))
Error in apply(lofGT_met, 1, function(x){(any(x == 2)}) :
dim(X) must have a positive length
would you please let me know how to correct it?
Thanks
On Mon, Aug 10, 2015 at 3:27 PM, Sarah Goslee <sarah.goslee at gmail.com>
wrote:
> Easy enough (note that your column names are problematic, though)
>
> > mydata <- structure(list(X125 = c(0L, 1L, 2L, 0L, 2L), X255 = c(1L, 1L,
> + 1L, 1L, 0L), X558 = c(0L, 0L, 2L, 0L, 0L), X2366 = c(NA, NA,
> + 1L, NA, 0L), X177 = c(0L, 0L, 0L, 0L, 0L), X255.1 = c(0L, 1L,
> + 0L, 0L, 0L)), .Names = c("X125", "X255", "X558", "X2366", "X177",
> + "X255.1"), class = "data.frame", row.names = c("aa", "bb", "cs",
> + "de", "gh"))
> > mydata$idx <- apply(mydata, 1, function(x)as.numeric(any(x == 2 & !is.na
> (x))))
> > mydata
> X125 X255 X558 X2366 X177 X255.1 idx
> aa 0 1 0 NA 0 0 0
> bb 1 1 0 NA 0 1 0
> cs 2 1 2 1 0 0 1
> de 0 1 0 NA 0 0 0
> gh 2 0 0 0 0 0 1
>
> Sarah
>
> On Mon, Aug 10, 2015 at 4:11 PM, Lida Zeighami <lid.zigh at gmail.com> wrote:
>
>> Hi there,
>>
>> I have a matrix contain 0,1,2, NA elements.
>> I want to add a column to this matrix with name of "idx" . then for each
>> row, I should put 1 in this column (idx) if there is at least one 2 in
>> that
>> row otherwise I should put 0 in this column!
>>
>> for example mydata:
>>
>> 125 255 558 2366 177 255
>> aa 0 1 0 NA 0 0
>> bb 1 1 0 NA 0 1
>> cs 2 1 2 1 0 0
>> de 0 1 0 NA 0 0
>> gh 2 0 0 0 0 0
>>
>>
>> my output should be:
>>
>>
>> 125 255 558 2366 177 255 idx
>> aa 0 1 0 NA 0 0 0
>> bb 1 1 0 NA 0 1 0
>> cs 2 1 2 1 0 0 1
>> de 0 1 0 NA 0 0 0
>> gh 2 0 0 2 0 2 1
>>
>> Thank you for your help.
>>
> --
> Sarah Goslee
> http://www.functionaldiversity.org
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list