【问题标题】:cbind throwing error in RR中的cbind抛出错误
【发布时间】:2017-10-09 13:28:39
【问题描述】:

我有一个维度为[1] 1 11[1] 3 29 的数据框。我正在尝试 cbind 这两个数据帧,以便将具有一行的数据帧复制三次到结果数据帧。

当我使用 cbind 时,它有时会工作,但会抛出错误

data.frame(..., check.names = FALSE) 中的错误:参数暗示不同的行数:1、3

> dim(a)
[1]  1 11
> dim (b)
[1]  3 29
> cbind(a,b)
Error in data.frame(..., check.names = FALSE) : 
arguments imply differing number of rows: 1, 3

但是,如果我尝试子集,它会起作用。

> cbind(a[1:10],b)  #Works Fine
> cbind(a[1:11],b) #Throws Error

注意:它有时会起作用,但如果我再次运行代码,它就不起作用了。

谢谢

【问题讨论】:

    标签: r


    【解决方案1】:

    请参考[cbind]documentation

    如果有多个矩阵参数,它们必须都具有相同的 列数(或行数),这将是列数(或 行)的结果。

    结果行将等于 a 和 b 的行号。

    【讨论】:

      【解决方案2】:

      如果你把它们做成数据表,那么你就不会再有错误了。

      cbind(iris[1:10, 1], iris[ 1:11,2:3]) # error
      
      cbind(iris[1:10, 1], iris[ 1:11,2]) # warning message, missing values are copied
      cbind(iris[1:10, 1], iris[ 1:11,2:3] %>% as.data.table()) # same
      cbind(iris[1:10, 1] %>% as.data.table(), iris[ 1:11,2:3] )# same
            . Sepal.Width Petal.Length
       1: 5.1         3.5          1.4
       2: 4.9         3.0          1.4
       3: 4.7         3.2          1.3
       4: 4.6         3.1          1.5
       5: 5.0         3.6          1.4
       6: 5.4         3.9          1.7
       7: 4.6         3.4          1.4
       8: 5.0         3.4          1.5
       9: 4.4         2.9          1.4
      10: 4.9         3.1          1.5
      11: 5.1         3.7          1.5
      
      
      # you can also make the extra values as zero or NA etc
      temp <- iris[1:10,1] %>% as.data.table()
      temp <- temp[match(rownames(iris[ 1:11,2:3]), rownames(temp[1:10, 1]))] 
      # temp[is.na(temp)] <- ""
      cbind(temp %>% as.data.table(), iris[ 1:11,2:3] )
      
            . Sepal.Width Petal.Length
       1: 5.1         3.5          1.4
       2: 4.9         3.0          1.4
       3: 4.7         3.2          1.3
       4: 4.6         3.1          1.5
       5: 5.0         3.6          1.4
       6: 5.4         3.9          1.7
       7: 4.6         3.4          1.4
       8: 5.0         3.4          1.5
       9: 4.4         2.9          1.4
      10: 4.9         3.1          1.5
      11:  NA         3.7          1.5
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-30
        • 2014-01-13
        • 1970-01-01
        • 1970-01-01
        • 2020-03-25
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        相关资源
        最近更新 更多