【问题标题】:R - using bind_rows for list of subsetted objectsR - 将 bind_rows 用于子集对象列表
【发布时间】:2017-07-02 21:24:39
【问题描述】:

我有一个下面结构的数十个对象的列表。我想删除每个文件的前三行,只保留前三列。

    x<-structure(c("", "Service", "", "HR", "", "", "Function", "", "Code", 
                "X1", "", "", "", "", "", "Doe, John", "Roe, Jane", 
                "Doe, Jane", "", "Full name", "", "", "", ""), .Dim = c(6L, 4L))

    y<-structure(c("", "Service", "", "IT", "", "", "Function", "", "Code", 
                "X2", "", "", "", "", "", "Doe, Johnny", "Roe, Janette", 
                "Doe, Janette", "", "Full name", "", "", "", ""), .Dim = c(6L, 4L))

    z<-structure(c("", "Service", "", "RD", "", "", "Function", "", "Code", 
                "X3", "", "", "", "", "", "Doe, Johnny", "Roe, Janette", 
                "Roe, Johnny", "", "Full name", "", "", "", ""), .Dim = c(6L, 4L))

l<-list(x,y,z)

如何用length(l) 概括列表中所有对象的下面写的内容?

length(l)

x<-bind_rows(
tbl_df(l[[1]][-c(1,2,3),c(1,2,3)]),
tbl_df(l[[2]][-c(1,2,3),c(1,2,3)]),
tbl_df(l[[3]][-c(1,2,3),c(1,2,3)])
)

【问题讨论】:

    标签: r list dplyr


    【解决方案1】:

    bind_rows可以接受数据框列表;因此,您可以遍历列表,对矩阵进行子集化并将它们转换为数据帧,然后bind_rows 应该可以处理结果列表:

    library(dplyr)
    bind_rows(lapply(l, function(mat) tbl_df(mat[-(1:3), 1:3])))
    
    # A tibble: 9 x 3
    #     V1    V2           V3
    #  <chr> <chr>        <chr>
    #1    HR    X1    Doe, John
    #2                Roe, Jane
    #3                Doe, Jane
    #4    IT    X2  Doe, Johnny
    #5             Roe, Janette
    #6             Doe, Janette
    #7    RD    X3  Doe, Johnny
    #8             Roe, Janette
    #9              Roe, Johnny
    

    另一种选择是使用do.call(rbind, ...),它会生成一个矩阵(如果您不在乎是矩阵或数据框):

    do.call(rbind, lapply(l, `[`, -(1:3), 1:3))
    
    #      [,1] [,2] [,3]          
    # [1,] "HR" "X1" "Doe, John"   
    # [2,] ""   ""   "Roe, Jane"   
    # [3,] ""   ""   "Doe, Jane"   
    # [4,] "IT" "X2" "Doe, Johnny" 
    # [5,] ""   ""   "Roe, Janette"
    # [6,] ""   ""   "Doe, Janette"
    # [7,] "RD" "X3" "Doe, Johnny" 
    # [8,] ""   ""   "Roe, Janette"
    # [9,] ""   ""   "Roe, Johnny"
    

    【讨论】:

      猜你喜欢
      • 2018-07-03
      • 2016-09-03
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 2022-12-05
      • 2019-07-13
      相关资源
      最近更新 更多