Reputation: 1259
I have a dataframe of dimensions[1] 1 11
and [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
Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 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
Upvotes: 0
Views: 4256
Reputation: 2133
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
Upvotes: 2
Reputation: 6325
Please refer [cbind]
documentation
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.
Upvotes: 2