Question

I have a large data frame that I need to subset based on a character string of row indices provided in a single column within another table (from outside of R). These strings include several styles of index (e.g. c(1,3), c(1:10,15), 3:10, but all are formats that should be acceptable to R. I've provided a small example here, but in practice the indices typically refer to large row chunks within a very large data frame, so I'm keen to stick with this approach if possible.

Example data:

my.df<-data.frame(group=c("a","a","b","b","c","c"),value=c(1,5,5,15,20,3))

set1<-"c(1,3)"

set2<-"c(1:3,5)"

what I'd like:

my.df[set1,]

group value
1     a     1
3     b     5


my.df[set2,]

group value
1     a     1
2     a     5
3     b     5

I can read the index strings into R successfully and convert them to a form that looks right as per the code above, but haven't been successful with the subsetting. I'm sure there's an easy trick so any help is much appreciated.

Was it helpful?

Solution

Something like this maybe

 my.df[eval(parse(text=set1)),]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top