Reputation: 390
I want to generate multiple data frames (df1, df2 etc.) based on one big data frame (df0). Each new data frame should consist of some mix of columns from df0.
df0 <- data.frame(v0=c(0, 0), v1=c(3, 4), v2=c(5, 6), v3=c(7, 8))
for(i in 1:3) {
secondcol <- colnames(df0[,..i]) # I get an error here
dfX = subset(df0, select = c("v0", secondcol)) # dfX should be df & i
}
# The for loop should replicate the following three comands:
df1 = subset(df0, select = c("v0", "v1"))
df2 = subset(df0, select = c("v0", "v2"))
df3 = subset(df0, select = c("v0", "v3"))
Upvotes: 0
Views: 72
Reputation: 3183
Many ways to do that. To make your code work as below:
library(dplyr)
for(i in 1:3) {
secondcol <- colnames(df0)[(i+1)]
dat <- select(df0, c("v0", secondcol))
assign(paste0("df", i), dat)
rm(dat)
}
@Rich solution is much better to manage. In case, you still want them as dataframes in your environment, you can use:
i <- 1:3
list2env(setNames(lapply(i+1, function(j) df0[c(1, j)]), paste0("df", i)), envir = .GlobalEnv)
Upvotes: 2
Reputation: 99321
I would recommend using a list to keep the resulting data frames organized. Here is an approach using lapply()
.
i <- 1:3
setNames(lapply(i+1, function(j) df0[c(1, j)]), paste0("df", i))
# $df1
# v0 v1
# 1 0 3
# 2 0 4
#
# $df2
# v0 v2
# 1 0 5
# 2 0 6
#
# $df3
# v0 v3
# 1 0 7
# 2 0 8
Upvotes: 4