假设我有两个向量。
v1<-c("a","b","c")
v2<-c("x","y","z")
我想要的是一个组合向量,它从一个到另一个完全交叉。但在此之前,载体中的每个元素都需要重复3次。
我想得到的最终载体是
a a a x x x a a a y y y a a a z z z b b b x x x b b b y y y .....
除了for-loop之外,是否有一种简单的方法可以使上面的矢量?
答案 0 :(得分:3)
使用rep:
#first, create necessary repeats in the two vectors in order to make one cross-product vector
v1_r <- rep(v1, each=3)
v2_r <- rep(v2, 3)
#combine them into one vector
v3 <- as.vector(rbind(v1_r,v2_r))
#add another repeat
v3_r <- rep(v3,each=3)
> v3_r
[1] "a" "a" "a" "x" "x" "x" "a" "a" "a" "y" "y" "y" "a" "a"
[15] "a" "z" "z" "z" "b" "b" "b" "x" "x" "x" "b" "b" "b" "y"
[29] "y" "y" "b" "b" "b" "z" "z" "z" "c" "c" "c" "x" "x" "x"
[43] "c" "c" "c" "y" "y" "y" "c" "c" "c" "z" "z" "z"
一行中的所有步骤:
v3_r <- rep(as.vector(rbind(rep(v1, each=3),rep(v2,3))),each=3)
答案 1 :(得分:0)
使用dplyr
包来替代@Heroka的替代方法。
v1<-c("a","b","c")
v2<-c("x","y","z")
library(dplyr)
data.frame(expand.grid(v1,v2)) %>% # create all combinations
mutate_each(funs(as.character)) %>% # transform to character
arrange(Var1) %>% # order by first column
rowwise() %>% # for each row
do(data.frame(vec=c(rep(.$Var1,3), rep(.$Var2,3)), stringsAsFactors=F)) # create a new vector by repeating the first element 3 times and then the second 3 times
# vec
# 1 a
# 2 a
# 3 a
# 4 x
# 5 x
# 6 x
# 7 a
# 8 a
# 9 a
# 10 y
# .. ...
不确定为什么更喜欢使用包而不是基础R,但以防其他人有类似问题(作为更大进程的一部分)并且他想使用dplyr方法。