2017-10-09 92 views
0

我有一个尺寸为[1] 1 11[1] 3 29的数据框。我试图将这两个数据帧绑定在一起,使得具有一行的数据帧将被复制三次到结果数据帧。cbind抛出错误R

当我使用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 

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

感谢

回答

1

请参阅[cbind]documentation

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

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

1

如果你让他们成为数据表,那么你就再也没有这个错误了。

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