From the help page of cbind
(?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. If all the arguments are vectors, the number of
columns (rows) in the result is equal to the length of the longest
vector. Values in shorter arguments are recycled to achieve this
length (with a warning if they are recycled only fractionally).
When the arguments consist of a mix of matrices and vectors the number
of columns (rows) of the result is determined by the number of columns
(rows) of the matrix arguments. Any vectors have their values recycled
or subsetted to achieve this length.
...
The cbind
data frame method is just a wrapper for data.frame(...,
check.names = FALSE)
. This means that it will split matrix columns in
data frame arguments, and convert character columns to factors unless
stringsAsFactors = FALSE
is specified.
I suspect that you are mixing up the number of rows. I'm not sure why you are getting your error with matrix()
, as you did not provide a reproducible example. Applying cbind
to data.frame()
throws an error because the number of rows do not match.
## this seems to work
cbind(matrix(),cor(1:10,2:11))
# [,1] [,2]
# [1,] NA 1
## this throws an error
cbind(data.frame(),1)
# Error in data.frame(..., check.names = FALSE) :
# arguments imply differing number of rows: 0, 1
You'd be better off avoiding the for-loop altogether and using apply
or sapply
:
sapply(seq_len(ncol(new_t)), function(i)
cor(x=new_t[,i], method='spearman', y=new_t[,12559]))