[英]How to create column based on vectors
I need to create one column based on two vectors that I had created.我需要根据我创建的两个向量创建一列。 This new column need to follow some rules.这个新列需要遵循一些规则。
Let say I have two vectors:假设我有两个向量:
vct_A <- c("AAA", "BBB", "CCC", "DDD", "EEE", "FFF")
vct_B <- c("P1", "P2", "P3")
The rules are:规则是:
The expected output is a data.frame
预期的输出是一个data.frame
vct_A vct_B
<chr> <chr>
1 AAA P1
2 AAA P2
3 AAA P3
4 BBB P1
5 BBB P2
6 BBB P3
7 CCC P1
8 CCC P2
9 DDD P2
10 DDD P3
11 EEE P4
12 FFF P4
Really need help on this.真的需要这方面的帮助。 Thanks谢谢
If there is no logic involved in selecting the values then we have to construct the dataframe manually.如果在选择值时不涉及逻辑,那么我们必须手动构建数据框。 One way using expand.grid
使用expand.grid
一种方法
df <- rbind(expand.grid(c("AAA", "BBB"), c("P1", "P2", "P3")),
expand.grid("CCC", c("P1", "P2")),
expand.grid("DDD", c("P2", "P3")),
expand.grid(c("EEE", "FFF"), "P3"))
df
# Var1 Var2
#1 AAA P1
#2 BBB P1
#3 AAA P2
#4 BBB P2
#5 AAA P3
#6 BBB P3
#7 CCC P1
#8 CCC P2
#9 DDD P2
#10 DDD P3
#11 EEE P3
#12 FFF P3
We can use tidyverse
methods我们可以使用tidyverse
方法
library(tidyverse)
list(crossing(Var1 = c("AAA", "BBB"), Var2 = c("P1", "P2", "P3")),
crossing(Var1 = "CCC", Var2 = c("P1", "P2")),
crossing(Var1 = "DDD", Var2 = c("P2", "P3")),
crossing(Var1 = c("EEE", "FFF"), Var2 = "P3")) %>%
bind_rows
# A tibble: 12 x 2
# Var1 Var2
# <chr> <chr>
# 1 AAA P1
# 2 AAA P2
# 3 AAA P3
# 4 BBB P1
# 5 BBB P2
# 6 BBB P3
# 7 CCC P1
# 8 CCC P2
# 9 DDD P2
#10 DDD P3
#11 EEE P3
#12 FFF P3
or using Map
from base R
或使用来自base R
Map
do.call(rbind, Map(expand.grid, split(vct_A, rep(1:4, c(2, 1, 1, 2))),
list(vct_B, vct_B[-3], vct_B[-1], vct_B[3])))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.