简体   繁体   中英

R Create Matrix From an Operation on a “Row” Vector and a “Column” Vector

First create a "row" vector and a "column" vector in R:

> row.vector <- seq(from = 1, length = 4, by = 1)
> col.vector <- {t(seq(from = 1, length = 3, by = 2))}

From that I'd like to create a matrix by, eg, multiplying each value in the row vector with each value in the column vector, thus creating from just those two vectors:

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    6   10
[3,]    3    9   15
[4,]    4   12   20

Can this be done with somehow using apply() ? sweep() ? ...a for loop?

Thank you for any help!

Here's a way to get there with apply . Is there a reason why you're not using matrix ?

> apply(col.vector, 2, function(x) row.vector * x)
##      [,1] [,2] [,3]
## [1,]    1    3    5
## [2,]    2    6   10
## [3,]    3    9   15
## [4,]    4   12   20

You'd be better off working with two actual vectors, instead of a vector and a matrix:

outer(row.vector,as.vector(col.vector))

#     [,1] [,2] [,3]
#[1,]    1    3    5
#[2,]    2    6   10
#[3,]    3    9   15
#[4,]    4   12   20

Simple matrix multiplication will work just fine

row.vector %*% col.vector
#      [,1] [,2] [,3]
# [1,]    1    3    5
# [2,]    2    6   10
# [3,]    3    9   15
# [4,]    4   12   20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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