I want to add a prefix to the colnames of dataframes in a list, based on the name of the dataframe:
list1 <- vector("list", 6)
list1 <- lapply(list1, function(x) data.frame(replicate(10,sample(0:1,10,rep=TRUE))))
list1 <- lapply(list1, function(x) {colnames(x)<- letters[1:10];x})
names(list1) <- LETTERS[1:6]
At this point, i want to change the colnames with something like:
colnames(list1[[1]]) <- paste(names(list1[1]), colnames(list1[[1]]), sep=".")
colnames(list1[[1]])
[1] "A.a" "A.b" "A.c" "A.d" "A.e" "A.f" "A.g" "A.h" "A.i" "A.j"
How can i do this sequentally on each of the six dataframes? I tried
lapply(list1, function(x) {colnames(list1[x]) <- paste(names(list1[x]), colnames(list1[[x]]), sep=".");x })
but
Error in list1[x] : invalid subscript type 'list'
I guess its about cycling through the names of list1? Or how is it done?
Thanks for your help.
CodePudding user response:
Using base R, you can use Map
.
Map(function(x, y) setNames(x, paste(names(x), y, sep = ".")), list1, names(list1))
Here is another way using purrr
. The i
functions (e.g., imap, imodify) will pass the name of the list item in as parameter .y
along with the list contents in .x
.
library(purrr)
imodify(list1, ~ set_names(.x, paste(names(.x), .y, sep = ".")))
CodePudding user response:
another way, if you have your dataframes already prepared and want to prefix columns with each dataframe's name:
## example dataframes
df1 <- data.frame(col1 = runif(1))
df2 <- data.frame(col1 = runif(1))
library(purrr)
dataframes_to_change = c('df1','df2')
walk(dataframes_to_change, ~{
df <- get(.x)
names(df) <- paste(.x, names(df), sep = '_')
assign(.x, value = df, pos = 1)
})
CodePudding user response:
Modifying attr
ibutes might be faster.
Map(`attr<-`, list1, 'names', Map(paste, names(list1), lapply(list1, attr, 'names'), sep='.'))