更改列表中列表的名称

时间:2018-06-27 14:49:46

标签: r list

根据模型名称(“ Bristol_A”,“ Bristol_B”和“ Bristol_C”)的不同,我将以下数据框分为三个列表

   a=c("Bristol_A","R1",358723.0,171704.0,1.0,36.818500,4.0222700,1.38895000)
   b=c("Bristol_A","R2",358723.0,171704.0,2.6,36.447300,4.0116100,1.37479000)
   c=c("Bristol_A","R3",358723.0,171704.0,5.0,35.615400,3.8092600,1.34301000)
   d=c("Bristol_B","R1",358723.0,171704.0,1.0,39.818300,2.4475600,1.50384000)
   e=c("Bristol_B","R2",358723.0,171704.0,2.6,39.391600,2.4209900,1.48754000)
   f=c("Bristol_B","R3",358723.0,171704.0,5.0,38.442700,2.3618400,1.45126000)
   g=c("Bristol_C","R1",358723.0,171704.0,1.0,31.246400,2.2388000,1.30652000)
   h=c("Bristol_C","R2",358723.0,171704.0,2.6,30.911600,2.2144800,1.29234000)
   i=c("Bristol_C","R3",358723.0,171704.0,5.0,30.166700,2.1603000,1.26077000)
   df=data.frame(a,b,c,d,e,f,g,h,i)
   df=t(df)
   df=data.frame(df)
   col_list=list("Model","Receptor.name","X(m.)","Y(m.)","Z(m.)",
          "nox","PM10","PM2.5")
   colnames(df)=col_list
   data_Report_list=split.data.frame(df, df$Model)
   list2env(split(df, df$Model), envir = .GlobalEnv) 

我希望实现的是将各个列表重命名为“ Model_A”(随后将其重命名为“ Model_B”,“ Model_C”等。

我当前的解决方案(无效)是:

    names(data_Report_list[1])="Model A"
    names(data_Report_list[2])="Model B"
    names(data_Report_list[3])="Model C"

但是,除了它不起作用之外,我还需要使脚本自动化,因此我不想单独写出每一行,而是让R识别出此列表中有X个文件,因此它更改了列表中的名称数量相同。例如,如果列表中有6个模型,R会将其命名为“ Model_A”至“ Model_F”。这有可能吗?

--------------------------------编辑-------------- --------------------

akrun的评论输出是这样的:

     $`Bristol_A`
         Model_A Receptor.name  X(m.)  Y(m.) Z(m.)     nox    PM10   PM2.5
    a Bristol_A            R1 358723 171704     1 36.8185 4.02227 1.38895
    b Bristol_A            R2 358723 171704   2.6 36.4473 4.01161 1.37479
    c Bristol_A            R3 358723 171704     5 35.6154 3.80926 1.34301 

但是我需要的是(第一行从“ Bristol_A”更改为“ Model_A”)

      $`Model_A`
        Model_A Receptor.name  X(m.)  Y(m.) Z(m.)     nox    PM10   PM2.5
      a Bristol_A            R1 358723 171704     1 36.8185 4.02227 1.38895
      b Bristol_A            R2 358723 171704   2.6 36.4473 4.01161 1.37479
      c Bristol_A            R3 358723 171704     5 35.6154 3.80926 1.34301

1 个答案:

答案 0 :(得分:1)

我们可以用list遍历Map并分配第一列名称

nm1 <- paste0("Model_", LETTERS[seq_along(data_Report_list)])
data_Report_list <- Map(function(x, y) {names(x)[1] <- y; x}, 
            data_Report_list, nm1)
names(data_Report_list) <- nm1
data_Report_list[1]
#$Model_A
#    Model_A Receptor.name  X(m.)  Y(m.) Z(m.)     nox    PM10   PM2.5
#a Bristol_A            R1 358723 171704     1 36.8185 4.02227 1.38895
#b Bristol_A            R2 358723 171704   2.6 36.4473 4.01161 1.37479
#c Bristol_A            R3 358723 171704     5 35.6154 3.80926 1.34301