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?
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.