我正在尝试使用expand()函数在列表向量中创建多个变量的组合。列出原子向量时,以下代码正确生成27行组合。但是,当我尝试以多种不同形式使用var_list时,expand()函数不会产生27种组合的预期结果。如何使用var_list动态创建数据帧df中多个列的组合?
abc <- letters[1:3]
num <- c(1,2,3)
xyz <- letters[24:26]
df <- as.data.frame(cbind(abc,num,xyz))
combinations_1 <- expand(df,abc,num,xyz) #This returns 27 combinations
var_list <- c("abc","num","xyz")
combinations_2 <- expand(df,var_list) #This returns 3 combinations
combinations_3 <- expand(df,df[var_list]) #This returns 3 combinations
combinations_4 <- expand(df,noquote(var_list)) #This returns 3 combinations
您可以使var_list
成为符号和拼接的列表。
library(tidyr)
df %>%
expand(!!!syms(var_list))
# A tibble: 27 x 3
abc num xyz
<fct> <fct> <fct>
1 a 1 x
2 a 1 y
3 a 1 z
4 a 2 x
5 a 2 y
6 a 2 z
7 a 3 x
8 a 3 y
9 a 3 z
10 b 1 x
# ... with 17 more rows
我们可以使用mget
返回对象名称的值
expand.grid(mget(var_list))
或使用expand
library(dplyr)
library(tidyr)
expand(df, !!! rlang::syms(var_list))
# A tibble: 27 x 3
# abc num xyz
# <fct> <fct> <fct>
# 1 a 1 x
# 2 a 1 y
# 3 a 1 z
# 4 a 2 x
# 5 a 2 y
# 6 a 2 z
# 7 a 3 x
# 8 a 3 y
# 9 a 3 z
#10 b 1 x
# … with 17 more rows