Welcome to the R community! It would help, if you could clarify your problem a little further with example code (input, desired output). I assume, that you're trying to create a new variable in every loop? Maybe the following helps:
Let's assume we'll do 3 iterations. I'll create a simple sample dataset with 2 columns
n <- 3
# create an example dataframe with 2 columns
df<- as.data.frame(rbind(c(1,1),c(2,2),c(1,2)))
colnames(df)<- c("v1","ID")
Next, create an empty data.frame. In your last step, you cannot join by the column ID if df.final does not have a column with that name!
`df.final <- data.frame(matrix(ncol = 2, nrow = 0))
colnames(df.final)<- c("v1","ID")
Let's do the for loop
for(i in 1:n) {
df[paste(colnames(df[1]),toString(i),sep ="_")] <- df[1]
if(i==n){
df.final <- df
} else {
df.final <- merge(df.final, df, by = "ID") #there is no point of doing the join in my example!
}
}
Since I am not sure, what exactly you wanted to do, I wrote some code, that copies the content of column 1 and writes it into a column that has the same name as column 1 plus a suffix of I. So let's look at the statement:
colnames(df[1]) gives you back the name of the first column of the dataframe as a string (var1)
toString(i) converts your iterator i to a string
By using the baste function with a sep ="_" you combine the name of the first column and your iterator to one string.
df["varname"]
is a way to refer to a column in a dataframe.
Your output will look like this
v1 ID v1_1 v1_2 v1_3
1 1 1 1 1 1
2 2 2 2 2 2
3 1 2 1 1 1
Hope that helps!
df? Maybe you can show us two steps of your desired process?