I have an R data frame dftotal
i A B C D
1 4 15 4 12
2 13 4 4 7
3 1 1 3 8
4 3 11 1 9
I want to write a loop that goes through the columns (A,B,C,D) and creates a new data frame each time, so that I have a data frame for each column:
dfA:
i A
1 4
2 13
3 1
4 3
And dfB:
i B
1 15
2 4
3 1
4 11
Etc...
I tried:
List <- colnames(dftotal)
List <- List[-1]
for (j in length(List))
{
df <- data.frame(dftotal$i,dftotal[List[j]])
assign(paste("df",List[j]), df)
}
But that returned a data frame only for the last column in my list. It seems to have overwritten the other data frames that were created in the loop.
df <- data.frame(dftotal$i,dftotal[List[1]])
assign(paste("df",List[1]), df)
Works fine, when I run it column by column manually.
What am I doing wrong?