代码之家  ›  专栏  ›  技术社区  ›  Maganna Dev

从最小可用向量创建数据帧

  •  0
  • Maganna Dev  · 技术社区  · 6 年前

    我想从数据帧列表中创建一个数据帧,特别是从这些数据帧的某一列中。但是,每个数据帧都包含不同数量的观察结果,因此下面的代码给出了一个错误。

    diffs <- data.frame(sensor1 = sensores[[1]]$Diff,
                        sensor2 = sensores[[2]]$Diff,
                        sensor3 = sensores[[3]]$Diff,
                        sensor4 = sensores[[4]]$Diff,
                        sensor5 = sensores[[5]]$Diff)
    

    错误:

    Error in data.frame(sensor1 = sensores[[1]]$Diff, sensor2 = sensores[[2]]$Diff,  : 
    arguments imply differing number of rows: 29, 19, 36, 26
    

    有什么方法可以强制data.frame()从每一列中获取最少的行数,在本例中是19?

    也许R中有一个内置函数可以做到这一点,任何解决方案都值得赞赏,但我希望得到尽可能一般和清晰的东西。

    提前谢谢你。

    1 回复  |  直到 6 年前
        1
  •  1
  •   coffeinjunky    6 年前

    我可以想到两种方法:

    示例数据:

    df1 <- data.frame(A = 1:3)
    df2 <- data.frame(B = 1:4)
    df3 <- data.frame(C = 1:5)
    

    计算最小数据帧的行数:

    min_rows <- min(sapply(list(df1, df2, df3), nrow))
    

    组合时使用子集:

    diffs <- data.frame(a = df1[1:min_rows,], b = df2[1:min_rows,], c = df3[1:min_rows,] )
    diffs
      a b c
    1 1 1 1
    2 2 2 2
    3 3 3 3
    

    或者,使用 merge :

    rowmerge <- function(x,y){
       # create row indicators for the merge:
       x$ind <- 1:nrow(x)
       y$ind <- 1:nrow(y)
       out <- merge(x,y, all = T, by = "ind")
       out["ind"] <- NULL
       return(out)
    }
    Reduce(rowmerge, list(df1, df2, df3))
       A  B C
    1  1  1 1
    2  2  2 2
    3  3  3 3
    4 NA  4 4
    5 NA NA 5
    

    为了摆脱争吵 NA s,移除 all = T .

    对于你的特殊情况,你可能会打电话给 Reduce(rowmerge, sensores) ,假设 sensores 是数据帧的列表。

    注意:如果您已经在某个地方有一个索引(例如某种时间戳),那么最好在该索引上合并,而不是创建 ind .