Creating multiple varibales in for loop

Hi all

Believe it or not, I can't find a simple answer to this. Let's say I have a df called mydata with variables id, name, qty and there is already data in those.
I want to add columns to that existing df so it becomes id, name, qty, s1, s2, ..., s88. Trouble is - I want to create 88 of them and I don't want to do

mydata$s1 <- 0
mydata$s2 <- 0
mydata$s88 <- 0

For the life of me, I can't find out how to do this in a simple for loop. Showing my inexperience here I know, but I've tried:
for (i in 1:88)
eval(paste('s$', i, ' <- 0')

but this doesn't work.

It must be simple - and I have tried searching - but not turned anything up.


This can be done without a loop, as shown below where I add four columns to a data frame. I think one reason you had trouble finding a method is that it is unlikely you need to do this. What is your larger goal?

DF <- data.frame(A=1:4, B = 2:5)
NewNames <- paste0("S", 1:4)
DF[NewNames] <- 0
#>   A B S1 S2 S3 S4
#> 1 1 2  0  0  0  0
#> 2 2 3  0  0  0  0
#> 3 3 4  0  0  0  0
#> 4 4 5  0  0  0  0

Created on 2020-09-01 by the reprex package (v0.3.0)

1 Like

thanks FJCC - that's brilliant - and does expose my inexperience. So what sort of object is NewNames in your example?

NewNames is a character vector. It could be constructed like this

NewNames <- c("S1", "S2", "S3", "S4")

but that gets tedious. The paste0() function prefixes the "S" to each element of the numeric vector produced by 1:4 and returns a character vector.
I am still interested to learn why you want to make columns full of zeros.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.