0
votes

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, e.g., 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!

3

3 Answers

2
votes

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
1
votes

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
1
votes

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