1

I'm trying to get subset of my data in R. I tried this, but I got unexpected result!

>str(data)
num [1:500, 1:2000] 5.65
>y<-c("rowname1"   , "rowname2", ... )
> spotA<-data[y]

NULL
> spotA
 [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA

also I tried as following way :

>spotA<-data[c("rowname1"   , "rowname2", ... )]

and I got the above result. what I would expect is to get sotA with dimension 16 2000 with numeric entries, not NA ! can somebody help me where is my mistake ?

user2806363
  • 2,513
  • 8
  • 29
  • 48
  • 3
    Please read the [FAQ on how to create a great reproducible example](http://stackoverflow.com/a/5963610/1412059). – Roland Sep 23 '13 at 14:26
  • It looks like you are using `data.table` syntax (Which does not require the comma after the `i` argument) and possibly confusing it with `data.frame` syntax (comma after the `i` is required) – Ricardo Saporta Sep 23 '13 at 14:42
  • 2
    @RicardoSaporta But `data` seems to be a matrix ... – Roland Sep 23 '13 at 14:52
  • 1
    @Roland, you're totally right. I should edit my comment to replace data.framr with matrix (but SO won't allow). Still I wonder if the confusion stems from reading other code & not realizing the class of the object. – Ricardo Saporta Sep 23 '13 at 15:18

1 Answers1

1

Try this:

data<-as.data.frame(matrix(runif(20),nrow=10,ncol=2));
y<-paste("row",row.names(data),sep=".")
row.names(data)<-y
data;
             V1         V2
row.1  0.3108385 0.09000282
row.2  0.3254967 0.44500053
row.3  0.3993356 0.71400316
row.4  0.2039391 0.11712378
row.5  0.4105687 0.70830021
row.6  0.5245575 0.36039628
row.7  0.2277783 0.71712201
row.8  0.6282813 0.33950400
row.9  0.1005018 0.94331287
row.10 0.3843297 0.58610738

data[row.names(data)%in%y[c(2,4,5,8,9)],]
             V1        V2
row.2 0.3254967 0.4450005
row.4 0.2039391 0.1171238
row.5 0.4105687 0.7083002
row.8 0.6282813 0.3395040
row.9 0.1005018 0.9433129
  • Huh; I never knew there was a `row.names` alternative to `rownames`. Anyway, the OP is correct that you could also write `data[c('row.1','row.8'),]`, right? Also, you could leave the OP's data structure as-is (as a matrix instead of a data.frame)... – Frank Sep 23 '13 at 16:13