我有两个这样的矢量:
a <- c(a,b,c)
b <- c(1,2,3)
我想创建一个如下所示的矩阵:
z <- matrix(c('a','a','a','b','b','b','c','c','c',1,2,3,1,2,3,1,2,3),nrow=9)
z
[,1] [,2]
[1,] "a" "1"
[2,] "a" "2"
[3,] "a" "3"
[4,] "b" "1"
[5,] "b" "2"
[6,] "b" "3"
[7,] "c" "1"
[8,] "c" "2"
[9,] "c" "3"
我如何在R?
中执行此操作答案 0 :(得分:1)
您可以使用expand.grid
:
a <- c("a","b","c")
b <- c(1,2,3)
expand.grid(a, b)
Var1 Var2
1 a 1
2 b 1
3 c 1
4 a 2
5 b 2
6 c 2
7 a 3
8 b 3
9 c 3
答案 1 :(得分:1)
您也可以使用:
library(data.table)
as.matrix(CJ(a,b))
# V1 V2
#[1,] "a" "1"
#[2,] "a" "2"
#[3,] "a" "3"
#[4,] "b" "1"
#[5,] "b" "2"
#[6,] "b" "3"
#[7,] "c" "1"
#[8,] "c" "2"
#[9,] "c" "3"