Hello!
# I have got this dataframe:
a <- c(10,20,30,40)
b <- c(15,25,35,45)
c <- c(20,30,40,50)
df <- data.frame(a,b,c)
df
# a b c
# 1 10 15 20
# 2 20 25 30
# 3 30 35 40
# 4 40 45 50
# And this list:
v1 <- c(1,2)
v2 <- c(2,4)
v3 <- c(3,4)
list <- list(v1,v2,v3)
list
# [[1]]
# [1] 1 2
# [[2]]
# [1] 2 4
# [[3]]
# [1] 3 4
I would like to subset my dataframe based on the elements in the list. The elements in the list represent the index of the dataframe. And I would like to store the subsetted dataframes in a new list.
Here is my solution:
df1 <- df[list[[1]],]
df2 <- df[list[[2]],]
df3 <- df[list[[3]],]
df_list <- list(df1,df2,df3)
df_list
# [[1]]
# a b c
# 1 10 15 20
# 2 20 25 30
# [[2]]
# a b c
# 2 20 25 30
# 4 40 45 50
# [[3]]
# a b c
# 3 30 35 40
# 4 40 45 50
Unfortunately, my real list and dataframe are very huge. Therefore, I would like to include all components of the list in one code line. Something like that:
df_list <- df[list[[1:3]], ]
but this doesn't work.
Someone here, who could help me?