Gabriel Hernandez
Gabriel Hernandez

Reputation: 85

Modifying column names of dataframes within a list

Working with lists of dataframes like so

library(data.table)
IDn = c("ChrM", "ChrM" ,"ChrM" ,"ChrM" ,"ChrM")   
posn = c(2,5,7,8,9)
met = c(2,0,4,1,0)
nmet = c(2,1,0,2,0)
bd = c(3,3,0,8,10)
dfp = data.frame(IDn,posn,met,nmet,bd)
  IDn     posn met  nmet bd
1 ChrM    2    2    2    3
2 ChrM    5    0    1    3
3 ChrM    7    4    0    0
4 ChrM    8    1    2    8
5 ChrM    9    0    0    10
L1<-list(d1=dfp, d2=dfp, d3=dfp)
    $d1
   IDn posn met nmet bd
1 ChrM    2   2    2  3
2 ChrM    5   0    1  3
3 ChrM    7   4    0  0
4 ChrM    8   1    2  8
5 ChrM    9   0    0 10

$d2
   IDn posn met nmet bd
1 ChrM    2   2    2  3
2 ChrM    5   0    1  3
3 ChrM    7   4    0  0
4 ChrM    8   1    2  8
5 ChrM    9   0    0 10

$d3
   IDn posn met nmet bd
1 ChrM    2   2    2  3
2 ChrM    5   0    1  3
3 ChrM    7   4    0  0
4 ChrM    8   1    2  8
5 ChrM    9   0    0 10

I want to change, for example, the name of the bd column to bd and the name of the df;

I tried using lapply and paste0("bd",names(l1)), but this one adds up the 3 names when I only need one per df.

Upvotes: 0

Views: 64

Answers (1)

Pierre L
Pierre L

Reputation: 28461

We can use Map to wrap the logic that you alluded to in the question:

Map(function(df,i) {names(df)[5] <- paste0("bd", names(L1)[i]);df}, L1, 1:length(L1))
# $d1
#    IDn posn met nmet bdd1
# 1 ChrM    2   2    2    3
# 2 ChrM    5   0    1    3
# 3 ChrM    7   4    0    0
# 4 ChrM    8   1    2    8
# 5 ChrM    9   0    0   10
# 
# $d2
#    IDn posn met nmet bdd2
# 1 ChrM    2   2    2    3
# 2 ChrM    5   0    1    3
# 3 ChrM    7   4    0    0
# 4 ChrM    8   1    2    8
# 5 ChrM    9   0    0   10
# 
# $d3
#    IDn posn met nmet bdd3
# 1 ChrM    2   2    2    3
# 2 ChrM    5   0    1    3
# 3 ChrM    7   4    0    0
# 4 ChrM    8   1    2    8

For data.table you can try:

for(i in 1:length(L1)) setnames(L1[[i]], "bd", paste0("bd", names(L1)[i]))

Upvotes: 4

Related Questions