如何在向量集上展开.grid 而不是单个元素 [英] How to expand.grid on vectors sets rather than single elements

查看:21
本文介绍了如何在向量集上展开.grid 而不是单个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有以下四个向量

So, I have the following four vectors

a1 <- c(11, 12)
a2 <- c(21, 22)

b1 <- c(31, 32)
b2 <- c(41, 42)

我最终想要的是一个看起来像

and what I want to have in the end is a data frame that looks like

  p1 p2 p3 p4
1 11 12 31 32
2 21 22 31 32
3 11 12 41 42
4 21 22 41 42

即两个 a 向量与两个 b 向量的所有可能组合.

i.e. every possible combination of the two a vectors with the two b vectors.

我所做的是

ab <-  expand.grid(list(a1, a2), list(b1,b2))
ab.new <- ab %>% separate(Var1, c("p1", "p2"), sep = ",") 
             %>% separate(Var2, c("p3", "p4"), sep = ",")

我最终得到的是

    p1   p2   p3   p4
1 c(11  12) c(31  32)
2 c(21  22) c(31  32)
3 c(11  12) c(41  42)
4 c(21  22) c(41  42)

那些 c( 在那里做了什么以及如何把它们弄出来?或者,我在使用 %>% 时做错了什么?

What are those c(s doing in there and how to get them out? Or, what did I do wrong in using %>%?

推荐答案

我们可以试试

do.call(cbind,lapply(expand.grid(list(a1, a2), list(b1,b2)),
               function(x) matrix(do.call(c, x), 4, 2, byrow=TRUE)))
#     [,1] [,2] [,3] [,4]
#[1,]   11   12   31   32
#[2,]   21   22   31   32
#[3,]   11   12   41   42
#[4,]   21   22   41   42

这篇关于如何在向量集上展开.grid 而不是单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆