Jared
Jared

Reputation: 111

Successively add columns to dataframe in R

I am looking to go through 20 iterations where I add 1 new column to an existing dataframe in each iteration. The column will be a value from the random uniform distribution between 1 and 100. My actual dataframes are 10000 rows, but the format of the dataframes is as follows:

df <- data.frame(var1 = c(319, 77, 222, 107, 167),
                  var2 = c(137, 290, 237, 52, 192),
                  class = c(1,1,0,1,0))

Ideally, the columns added will be named var3, var4,...., var21 with each iteration. I need to fit some models after each iteration as each individual column is added to the dataframe, in order to show how their accuracy declines as more columns are added of information that is not helpful.

Upvotes: 0

Views: 528

Answers (2)

David Ranzolin
David Ranzolin

Reputation: 1084

Since you already have var1 and var2, you could iterate through 3 to 20 with a for loop:

for (i in 3:20) {
  col_name <- paste0("var", i)
  df[[col_name]] <- runif(5, 0, 100) #5 because df has 5 rows
}

This will create vars3, var4, ...var 20.

Upvotes: 1

Suhas Shastry
Suhas Shastry

Reputation: 76

df <- data.frame(var1 = c(319, 77, 222, 107, 167),
                  var2 = c(137, 290, 237, 52, 192),
                  class = c(1,1,0,1,0))
for(i in 1:20){
col = paste('var_new_',i)
df[col] = runif(5)
# Add model code here
}
df

Upvotes: 1

Related Questions