EcologyTom
EcologyTom

Reputation: 2500

Paste element name onto columns in each list element

I have a list of dataframes. Each list element has a unique name but the column names are identical across all data frames.

I would like to paste the name of each dataframe to the columns, so that when I cbind them together into a single large dataframe I can distinguish between them.

Example data;

LIST <- list(df1 = data.frame("ColA" = c(1:5), "ColB" = c(10:14)), 
             df2 = data.frame("ColA" = c(21:25), "ColB" = c(30:34)))

str(LIST)

List of 2
 $ df1:'data.frame':    5 obs. of  2 variables:
  ..$ ColA: int [1:5] 1 2 3 4 5
  ..$ ColB: int [1:5] 10 11 12 13 14
 $ df2:'data.frame':    5 obs. of  2 variables:
  ..$ ColA: int [1:5] 21 22 23 24 25
  ..$ ColB: int [1:5] 30 31 32 33 34

Desired output;

List of 2
     $ df1:'data.frame':    5 obs. of  2 variables:
      ..$ df1.ColA: int [1:5] 1 2 3 4 5
      ..$ df1.ColB: int [1:5] 10 11 12 13 14
     $ df2:'data.frame':    5 obs. of  2 variables:
      ..$ df2.ColA: int [1:5] 21 22 23 24 25
      ..$ df2.ColB: int [1:5] 30 31 32 33 34

Upvotes: 2

Views: 1106

Answers (3)

Cettt
Cettt

Reputation: 11981

Hi you can use map2 to do this:

library(tidyverse)
map2(mylist, names(mylist), ~rename_all(.x, function(z) paste(.y, z, sep = ".")))

EDIT: or as suggested in the commenst use imap

imap(mylist, ~rename_all(.x, function(z) paste(.y, z, sep = ".")))

Upvotes: 1

jay.sf
jay.sf

Reputation: 72633

You could do this in a lapply with global assignment <<-.

lapply(seq_along(LIST), function(x) 
  names(LIST[[x]]) <<- paste0(names(LIST)[x], ".", names(LIST[[x]])))

Or using Map as @Sotos suggested

LIST <- Map(function(x, y) {names(x) <- paste0(y, '.', names(x)); x}, LIST, names(LIST))

Yields

str(LIST)
# List of 2
# $ df1:'data.frame':   5 obs. of  2 variables:
#   ..$ df1.ColA: int [1:5] 1 2 3 4 5
# ..$ df1.ColB: int [1:5] 10 11 12 13 14
# $ df2:'data.frame':   5 obs. of  2 variables:
#   ..$ df2.ColA: int [1:5] 21 22 23 24 25
# ..$ df2.ColB: int [1:5] 30 31 32 33 34

Upvotes: 2

markus
markus

Reputation: 26343

Since you mention that you want to use cbind later, you might use as.data.frame right away

as.data.frame(LIST)
#  df1.ColA df1.ColB df2.ColA df2.ColB
#1        1       10       21       30
#2        2       11       22       31
#3        3       12       23       32
#4        4       13       24       33
#5        5       14       25       34

Thanks to @RonakShah you can use the following lines to get back a list in case you need it

df1 <- as.data.frame(LIST)
split.default(df1, sub("\\..*", "", names(df1)))

Upvotes: 4

Related Questions