英文:
Creating a 'Table' From Two Data-Sets
问题
我有两个4x1矩阵,我想要将其中一个矩阵的每个项与另一个矩阵的所有4个项相乘。我最好的描述方法是,我希望编写R代码,以产生附加的照片中显示的4x4矩阵。
rm(list = ls())
cat("4")
graphics.off()
x <- c(1,2,3,4)
y <- c(5,2,1,2)
我遇到的问题是,我只得到一个4x1矩阵,而不是所期望的4x4矩阵,如下所示。
期望的结果:
英文:
I have two 4x1 matrices with which I would like to multiply each term in one with all 4 terms in the other. The best way I can describe it is I wish to write R code that will yield the 4x4 matrix shown in the photo attached.
rm(list = ls())
cat("4")
graphics.off()
x<- c(1,2,3,4)
y<- c(5,2,1,2)
The problem I am having is that I am only getting back a 4x1 matrix, as opposed to the desired 4x4 shown below
Desired Result
答案1
得分: 1
请注意,您期望的结果仅是矩阵相乘的结果:
> matrix(y) %*% x
[,1] [,2] [,3] [,4]
[1,] 5 10 15 20
[2,] 2 4 6 8
[3,] 1 2 3 4
[4,] 2 4 6 8
英文:
Note that your expected result is just the result of a matrix multiplication:
> matrix(y) %*% x
[,1] [,2] [,3] [,4]
[1,] 5 10 15 20
[2,] 2 4 6 8
[3,] 1 2 3 4
[4,] 2 4 6 8
答案2
得分: 1
你有多种方法可以做到这一点,例如,
> outer(y, x)
[,1] [,2] [,3] [,4]
[1,] 5 10 15 20
[2,] 2 4 6 8
[3,] 1 2 3 4
[4,] 2 4 6 8
> kronecker(y, t(x))
[,1] [,2] [,3] [,4]
[1,] 5 10 15 20
[2,] 2 4 6 8
[3,] 1 2 3 4
[4,] 2 4 6 8
> y %x% t(x)
[,1] [,2] [,3] [,4]
[1,] 5 10 15 20
[2,] 2 4 6 8
[3,] 1 2 3 4
[4,] 2 4 6 8
英文:
You have many ways to make it, e.g.,
> outer(y, x)
[,1] [,2] [,3] [,4]
[1,] 5 10 15 20
[2,] 2 4 6 8
[3,] 1 2 3 4
[4,] 2 4 6 8
> kronecker(y, t(x))
[,1] [,2] [,3] [,4]
[1,] 5 10 15 20
[2,] 2 4 6 8
[3,] 1 2 3 4
[4,] 2 4 6 8
> y %x% t(x)
[,1] [,2] [,3] [,4]
[1,] 5 10 15 20
[2,] 2 4 6 8
[3,] 1 2 3 4
[4,] 2 4 6 8
答案3
得分: 0
请尝试使用sapply
函数
sapply(x, `*`, y)
[,1] [,2] [,3] [,4]
[1,] 5 10 15 20
[2,] 2 4 6 8
[3,] 1 2 3 4
[4,] 2 4 6 8
还可以使用purrr::map
函数
len <- length(x)
map(x, ~ .x*y) %>% as.data.frame() %>% setNames(1:len)
1 2 3 4
1 5 10 15 20
2 2 4 6 8
3 1 2 3 4
4 2 4 6 8
英文:
Please try the sapply
sapply(x, `*`, y)
[,1] [,2] [,3] [,4]
[1,] 5 10 15 20
[2,] 2 4 6 8
[3,] 1 2 3 4
[4,] 2 4 6 8
also with purrr::map
len <- length(x)
map(x, ~ .x*y) %>% as.data.frame() %>% setNames(1:len)
1 2 3 4
1 5 10 15 20
2 2 4 6 8
3 1 2 3 4
4 2 4 6 8
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论