1

I have a data set with the columns:

A1,B1,C1,A2,B2,C2...., A100,B100,C100.

I want to create multiple dataframe: data1 = cbind(A1,B1,C1), data2 = cbind(A2,B2,C3)......

My Pseudo code:

For i from 1 to 100 {
Data[i]= cbind(A[i],B[i],C1[i])
} 

I think using [i] to present the column is wrong.

And How could I create multiple dataframe using the loop? Thanks!

Sotos
  • 51,121
  • 6
  • 32
  • 66
Monkey2018
  • 13
  • 2
  • As in @Sotos' answer, I suggest keeping the frames within a `list` instead of trying to deal with them as individual variables. My guess is that they are structured similarly, meaning you'll be applying the same function(s) to all of them, ergo `lapply` and friends. Ref: https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207 – r2evans Apr 18 '18 at 15:01

1 Answers1

2

You can use split.default to do that, i.e.

set.seed(666)
df <- data.frame(A1 = sample(5, 5), A2 = sample(5, 5), 
                 B1 = sample(5, 5), B2 = sample(5, 5), 
                 stringsAsFactors = FALSE)

split.default(df, gsub('\\D+', '', names(df)))

which gives,

$`1`
  A1 B1
1  4  4
2  1  1
3  3  5
4  5  3
5  2  2

$`2`
  A2 B2
1  4  5
2  5  1
3  2  3
4  1  4
5  3  2
Sotos
  • 51,121
  • 6
  • 32
  • 66