简体   繁体   English

R中的Cbind投掷错误

[英]cbind throwing error in R

I have a dataframe of dimensions [1] 1 11 and [1] 3 29 . 我有一个尺寸为[1] 1 11[1] 3 29的数据框。 I am trying to cbind these two dataframes such that dataframe having one row will be copied thrice to the resultant dataframe. 我正在尝试绑定这两个数据帧,以便将具有一行的数据帧复制三次到结果数据帧。

When I use cbind, it works sometimes but throws error as 当我使用cbind时,它有时可以工作,但是会抛出错误

Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 1, 3 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

However if I try subsetting, it works. 但是,如果我尝试子设置,它会起作用。

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

Note: It works sometimes, but doesn't work if I run the code again. 注意:它有时可以工作,但是如果我再次运行代码,则不能工作。

Thanks 谢谢

Please refer [cbind] documentation 请参考[cbind] 文档

If there are several matrix arguments, they must all have the same number of columns (or rows) and this will be the number of columns (or rows) of the result. 如果有多个矩阵参数,则它们必须全部具有相同的列(或行)数,这将是结果的列(或行)数。

The resultant row will be equal to the row number of a and b. 结果行将等于a和b的行号。

If you make them data tables then you do not have the error anymore. 如果使它们成为数据表,则不会再有错误。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM