我需要根据创建的两个向量创建一列。此新列需要遵循一些规则。
假设我有两个向量:
vct_A <- c("AAA", "BBB", "CCC", "DDD", "EEE", "FFF")
vct_B <- c("P1", "P2", "P3")
规则是:
预期输出为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
真的需要帮助。谢谢
答案 0 :(得分:1)
如果选择值没有逻辑,那么我们必须手动构造数据框。一种使用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
答案 1 :(得分:0)
我们可以使用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
或使用Map
中的base R
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])))