I am transforming this dataframe into a list with separate dataframes
df <- data.frame(1:10, 11:20, letters[seq(from=1, to=10)])
colnames(df) <- c(letters[seq(from=1,to=3)])
list.df <- lapply(df[,1:2], function(j) {
data.frame(j, df$c)
})
but I want to set the name the first column name to be the same as the name of the list (a and b respectively). While in this exemple, inside each list, the first column of the dataframe is always "j".
How could I do that???
Also, how could I change the second column from "df.c" to anything else??
Thanks
CodePudding user response:
Iterate over the column number and subset the dataframe to get the same name as original column names. Use cbind
to bind c
column and assign name of your choice.
lapply(1:2, function(i) cbind(df[i], new_name = df$c))
#[[1]]
# a new_name
#1 1 a
#2 2 b
#3 3 c
#4 4 d
#5 5 e
#6 6 f
#7 7 g
#8 8 h
#9 9 i
#10 10 j
#[[2]]
# b new_name
#1 11 a
#2 12 b
#3 13 c
#4 14 d
#5 15 e
#6 16 f
#7 17 g
#8 18 h
#9 19 i
#10 20 j
CodePudding user response:
we can use parent.frame()
to get the current column index and set its name;
df <- data.frame(1:10, 11:20, letters[seq(from=1, to=10)])
colnames(df) <- c(letters[seq(from=1,to=3)])
list.df <- lapply(df[,1:2], function(j) {
name_index <- parent.frame()$i
name_to_set <- colnames(df[,1:2])[name_index]
subdf <- data.frame(j,the_name_you_wish = df$c)
colnames(subdf) <- gsub('j',name_to_set,colnames(subdf))
subdf
})
also set a new name to df$c
output;
$a
a the_name_you_wish
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
6 6 f
7 7 g
8 8 h
9 9 i
10 10 j
$b
b the_name_you_wish
1 11 a
2 12 b
3 13 c
4 14 d
5 15 e
6 16 f
7 17 g
8 18 h
9 19 i
10 20 j
CodePudding user response:
df <- data.frame(1:10, 11:20, letters[seq(from=1, to=10)])
colnames(df) <- c(letters[seq(from=1,to=3)])
library(dplyr, warn.conflicts = FALSE)
list.df <- lapply(1:2, function(j) {
df %>% select(!!!j, c)
})
list.df
#> [[1]]
#> a c
#> 1 1 a
#> 2 2 b
#> 3 3 c
#> 4 4 d
#> 5 5 e
#> 6 6 f
#> 7 7 g
#> 8 8 h
#> 9 9 i
#> 10 10 j
#>
#> [[2]]
#> b c
#> 1 11 a
#> 2 12 b
#> 3 13 c
#> 4 14 d
#> 5 15 e
#> 6 16 f
#> 7 17 g
#> 8 18 h
#> 9 19 i
#> 10 20 j
Created on 2022-02-25 by the reprex package (v2.0.1)
Or if you want to rename
df <- data.frame(1:10, 11:20, letters[seq(from=1, to=10)])
colnames(df) <- c(letters[seq(from=1,to=3)])
library(dplyr, warn.conflicts = FALSE)
list.df <- lapply(1:2, function(j) {
df %>% select(!!!j, newname = c)
})
list.df
#> [[1]]
#> a newname
#> 1 1 a
#> 2 2 b
#> 3 3 c
#> 4 4 d
#> 5 5 e
#> 6 6 f
#> 7 7 g
#> 8 8 h
#> 9 9 i
#> 10 10 j
#>
#> [[2]]
#> b newname
#> 1 11 a
#> 2 12 b
#> 3 13 c
#> 4 14 d
#> 5 15 e
#> 6 16 f
#> 7 17 g
#> 8 18 h
#> 9 19 i
#> 10 20 j
Created on 2022-02-25 by the reprex package (v2.0.1)