匹配并命名data.frames列,其中列名包含在列表中,data.frames包含在另一个列表

时间:2015-11-28 08:41:12

标签: r list

我正在编写一个函数,将名称,列名称与其各自的data.frames相匹配。这三个元素分别包含在一个列表中,其中列表包含三个包含三个元素的列表 - 一个列表包含data.frame的名称,另一个列表包含data.frames的列名称,另一个列表包含data.frames的列表。输出结合到一个包含所有data.frames的列表。

为了简单起见,我创建了以下数据示例:

lists.of.dfs<- structure(list(name = c("A", "B", "C"), 
 header = list(c("DATE", "NAME", "AGE"), c("CITY", "STREET"), 
 c("ID", "FIRST_NAME", "LAST_NAME")), 
 df = list(structure(c("2015-11-05","James", "15", "2015-11-05", "Jack", 
 "11", "2015-11-05", "Jim", "11"), .Dim = c(3L, 3L)),
 structure(c("Los Angeles", "Brougham", "Auckland", "Peel", "Darwin", 
 "Derby", "Dunedin", "Palmerston"), .Dim = c(4L,2L)), structure(c("11462",
 "Tony", "Eric", "23467", "Kane", "Grant", "907894", "Dolby", 
 "Fitzgerald"), .Dim = c(3L,3L)))))

我已经尝试过这样做但不起作用。

make.df<-function(lst){
         tbl<-lapply(1:length(lst$name), function (i){ names(lst$df[[i]])<- lst$headers[[i]]})
         names(tbl)<-lst$name
         return(tbl)
}

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

修复示例结构后(因为第二个矩阵已经转置,而其他矩阵没有转置),您可以使用以下代码:

lists.of.dfs<- structure(list(
  name = c("A", "B", "C"), 
  header = list(c("DATE", "NAME", "AGE"), 
                c("CITY", "STREET"), 
                c("ID", "FIRST_NAME", "LAST_NAME")), 
  df = list(structure(c("2015-11-05","James", "15", 
                        "2015-11-05", "Jack", "11", 
                        "2015-11-05", "Jim", "11"), 
                      .Dim = c(3L, 3L)),
            structure(c("Los Angeles", "Brougham", 
                        "Auckland", "Peel", 
                        "Darwin", "Derby", 
                        "Dunedin", "Palmerston"), 
                      .Dim = c(2L,4L)), 
            structure(c("11462","Tony", "Eric", 
                        "23467", "Kane", "Grant", 
                        "907894", "Dolby","Fitzgerald"), 
                      .Dim = c(3L,3L)))))

make.df<-function(lst){

  tbl<-lapply(1:length(lst$name), 
              function (i){ 
                  DF <- as.data.frame(t(lst$df[[i]]),stringsAsFactors=FALSE)
                  names(DF) <- lst$header[[i]]
                  return(DF)
              })
  names(tbl)<-lst$name
  return(tbl)
}

结果:

> make.df(lists.of.dfs)
$A
        DATE  NAME AGE
1 2015-11-05 James  15
2 2015-11-05  Jack  11
3 2015-11-05   Jim  11

$B
         CITY     STREET
1 Los Angeles   Brougham
2    Auckland       Peel
3      Darwin      Derby
4     Dunedin Palmerston

$C
      ID FIRST_NAME  LAST_NAME
1  11462       Tony       Eric
2  23467       Kane      Grant
3 907894      Dolby Fitzgerald