0

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?

Alex Kinman
  • 2,437
  • 8
  • 32
  • 51

2 Answers2

1

For the record - replying to the question of what you are doing wrong:

for (j in length(List))

should rather be

for (j in 1:length(List))

RolandASc
  • 3,863
  • 1
  • 11
  • 30
0

Assume these below are vectors

i <- c(1,2,3,4)
A <- c(4,13,1,3)
B <- c(15,4,1,11)
C <- c(4,4,3,1)
D <- c(12,7,8,9)

Data frame for all i, A, B, C, D

MM <- cbind(i,A,B,C,D)
MM <- data.frame(MM)

List <- colnames(MM)
List <- List [-1]

The function to create specific data frames df1, df2, df3 and df4

for (j in 1:length(List)) {

df <- data.frame(MM$i,MM[,List[j]]) colnames(df) <- c("i", paste("df",List[j], sep = "")) assign(paste("df",j, sep = ""),df) }