简体   繁体   English

如何将R中的向量合并到数据帧中?

[英]How to combine vectors in R into a dataframe?

Is there a more elegant way to do this? 有没有更优雅的方法可以做到这一点? a and b run in parallel, c and d form a cartesian product a和b并行运行,c和d形成笛卡尔积

a <- c("a","b","c")
b <- c("A","B","C")
c <- c(1,2,3)
d <- c(11,22)
nrow_cd <- length(c)*length(d)
nrow_abcd <- length(a)*nrow_cd
abcd <- data.frame(
    a=rep(a, each=nrow_cd),
    b=rep(b, each=nrow_cd),
    c=rep(c, each=length(d)),
    d=rep(d, times=nrow_abcd)
)    

abcd
   a b c  d
1  a A 1 11
2  a A 1 22
3  a A 2 11
4  a A 2 22
5  a A 3 11
6  a A 3 22
7  b B 1 11
8  b B 1 22
9  b B 2 11
10 b B 2 22
11 b B 3 11
12 b B 3 22
13 c C 1 11
14 c C 1 22
15 c C 2 11
16 c C 2 22
17 c C 3 11
18 c C 3 22
19 a A 1 11
20 a A 1 22
21 a A 2 11
22 a A 2 22
23 a A 3 11
24 a A 3 22
25 b B 1 11
26 b B 1 22
27 b B 2 11
28 b B 2 22
29 b B 3 11
30 b B 3 22
31 c C 1 11
32 c C 1 22
33 c C 2 11
34 c C 2 22
35 c C 3 11
36 c C 3 22

You can do this: 你可以这样做:

bcd  <- rev(expand.grid(list(d=d,c=c,b=b)))
abcd <- data.frame(a = a[match(bcd$b, b)], bcd)

It gives you 18 rows ie length(b)*length(c)*length(d) . 它为您提供18行,即length(b)*length(c)*length(d) I am not sure if you meant to have duplicates in your examples. 我不确定您是否要在示例中重复。 If it is the case, just add: 如果是这样,只需添加:

abcd <- rbind(abcd, abcd)

Did you mean to intentionally double your dataframe? 您是不是故意将数据框加倍? Rows 1:18 are identical to rows 19:36... 第1:18行与第19:36行...

Here's one solution 这是一个解决方案

a <- c("a","b","c")
b <- c("A","B","C")
c <- c(1,2,3)
d <- c(11,22)
nrow_cd <- length(c)*length(d)

ab <- sapply(list(a,b), rep, each=nrow_cd)
cd <- expand.grid(c,d)
out <- cbind(ab, cd[rep(rownames(cd),length=nrow(ab)),])
rownames(out) <- 1:nrow(out)
names(out ) <- letters[1:4]
out

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM