0

I have created an index in another dataframe called "index"

I1 I2 I3 ...
1  3  5
2  4  6 
3  5  7

I would like to subset another dataframe like so, and store each result as a separate dataframe

column_name_from_index <- main_df[index[,i], ]

So the end result is I get main_df indexed by columns of index, output being dataframes I1, I2, I3 and so on. I am getting stuck on splitting out my results (I am not grabbing column name at the moment, but I would like advice on how to do that).

s <- seq(1,30)
df <- main_df[FALSE, ] #creates an empty dataframe into which I can put all columns from main_df.

for(i in s){
df <- main_df[index[,i], ]
df[i, ]
}
cocanut
  • 179
  • 1
  • 8
  • 2
    `lapply(index, function(i) main_df[i, ] )` ? – Jaap Oct 11 '17 at 15:26
  • Anyway, it is always good to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). In your case, including example data for `main_df` (or the output of `dput(main_df)`) and the desired output would greatly benefit your question. – Jaap Oct 11 '17 at 15:28

1 Answers1

0

This will be more wieldy if you use a list instead of separate data frames. As Jaap shows, lapply is easy for this, and we can name the result:

index = data.frame(I1 = 1:3, I2 = 3:5)
main_df = data.frame(x = 1:6, y = 2:7)

result = lapply(index, function(i) main_df[i, ])
names(result) = names(index)
result
# $I1
#   x y
# 1 1 2
# 2 2 3
# 3 3 4
# 
# $I2
#   x y
# 3 3 4
# 4 4 5
# 5 5 6

You can access the individual data frames by number or name, e.g., result[["I2"]] or result[[2]]. See How to make a list of data frames? for a long discussion about why this is better than individual data frames (but also tips for converting the list to individual data frames for the exceptionally stubborn or masochistic).

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294