修改列表中数据框的列名称

时间:2016-02-09 23:06:42

标签: r list dataframe lapply

使用像这样的数据框列表

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

我想将bd列的名称更改为bd和df的名称;

我尝试使用lapplypaste0("bd",names(l1)),但是当我每df只需要一个名字时,这个名称会加起来。

1 个答案:

答案 0 :(得分:4)

我们可以使用Map来包含您在问题中提到的逻辑:

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

对于data.table,您可以尝试:

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