0

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"))

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.