I would like to make a loop that extracts every 3 column from my dataframe. The original dataframe length is not fix, so it could be 30 column or 12 long. The only thing what is fix that there will be 3 columns after each other I want to extract and put it into a list of dataframes.
For example:
KO5_1 KO5_2 KO5_3 KO9_1
1 1 3 3
2 0 0 3
2 2 3 0
0 0 1 2
and I want the KO5_1 KO5_2 KO5_3 to be extracted and put together in a separate df. The KO9 and the other 2 of its kind will go another df. The names are changing its just an example.
How can I make this loop?
Thank you!
CodePudding user response:
Let's use a sample data frame. The names aren't important.
set.seed(1)
df <- as.data.frame(replicate(10, sample(5)))
df
#> V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
#> 1 1 5 3 2 1 1 2 1 2 4
#> 2 4 3 5 5 3 2 5 4 5 2
#> 3 3 4 1 4 5 5 1 3 3 1
#> 4 5 2 4 3 4 3 4 2 4 3
#> 5 2 1 2 1 2 4 3 5 1 5
To get this into a list of 3 data frames comprising every 3rd column, we can do:
n <- 3
lapply(seq(n) %% n, function(i) df[seq_along(df) %% n == i])
#> [[1]]
#> V1 V4 V7 V10
#> 1 1 2 2 4
#> 2 4 5 5 2
#> 3 3 4 1 1
#> 4 5 3 4 3
#> 5 2 1 3 5
#>
#> [[2]]
#> V2 V5 V8
#> 1 5 1 1
#> 2 3 3 4
#> 3 4 5 3
#> 4 2 4 2
#> 5 1 2 5
#>
#> [[3]]
#> V3 V6 V9
#> 1 3 1 2
#> 2 5 2 5
#> 3 1 5 3
#> 4 4 3 4
#> 5 2 4 1
You can change n
to get every 4th column, 5th column, etc.
CodePudding user response:
Use split.default
, with gl(n, 3)
to split every three columns. Or gl(3, 1)
if you wanna get three groups of one column every three columns.
df <- as.data.frame(replicate(10, sample(5)))
names(df) <- paste0("K0", 1:10)
n = ceiling(ncol(df) / 3)
split.default(df, gl(n, 3))
$`1`
K01 K02 K03
1 2 3 3
2 4 1 5
3 3 2 2
4 1 5 1
5 5 4 4
$`2`
K04 K05 K06
1 5 4 4
2 4 3 2
3 2 5 1
4 3 2 3
5 1 1 5
$`3`
K07 K08 K09
1 3 4 1
2 5 5 3
3 1 1 2
4 4 3 5
5 2 2 4
$`4`
K010
1 3
2 5
3 1
4 4
5 2