I'm trying to make a script in Rstudio where I input some columns, then it outputs a new column for each column input. The problem is, I don't know how many columns will be input; this number will change. I'm trying to loop through to create the columns, but each command I know requires a name for the column and this is giving me trouble. I can create random names for the new columns, but I can't make the loop target the column names. Without names, I can't make any columns. I can put the names in nametable, but add_column doesn't seem to be able to target it for some reason.
If anyone can figure out how to add columns without names, or how to add them with names from this kind of function, I would really appreciate it.
colcount <- ncol(tdata)
nametable <- NULL
for (i in 2:(colcount)){
nametable[i] <- paste("v",i)
}
for (i in 2:(colcount)) {
idk4<- nametable[i]
tdata <- add_column(tdata,idk4,.after = colcount)
}
Corrected code:
rowcount <- nrow(tdata)
colcount <- ncol(tdata)
for (i in 2:ncol(tdata)){
to_add <- data.frame(name1 = 1:1248)
for (c in seq_len(ncol(to_add))) {
tdata[[paste0('v_',i-1)]] <- to_add[,c]
}}