I would like to subset a dataset into several smaller df's while using the names of columns in a for-loop.
Create some data (this can probably be done easier...)
Line1 <- c(1:7)
Line2 <- c(3:9)
df <- rbind(Line1, Line2)
ColumnNames <- c(paste0("Var", 1:7))
df <- lapply(df, setNames, ColumnNames)
colnames(df)=ColumnNames
As output I would like to have three dataframes: Df_Sub1, Df_Sub2 and Df_Sub3.
Sub1 <- c("Var1", "Var2", "Var3")
Sub2 <- c("Var3", "Var4")
Sub3 <- c("Var5", "Var6", "Var7")
Subs <- c("Sub1", "Sub2", "Sub3")
For loop to create the three subsets
for (Sub in Subs) {
name <- as.name(paste0("df_",Sub))
df_ <- df[,colnames(df) %in% get(Sub)]
}
How to stick name after df_ for each of the three Subs (or do something else to make this work)?
We can use
mgetto return the object values in alist, loop over thelist, select the columns of 'df', and create the objects in global env withlist2env-output