首页 > 解决方案 > 从列表中填充 df 的缺失变量

问题描述

我在列表中缺少分类变量。我想将这些分类的所有组合添加到使用complete. 我可以使用mutate. 简化示例:

library(tidyverse)
df <- tibble(a1 = 1:6,
             b1 = rep(c(1,2),3),
             c1 = rep(c(1:3), 2))

missing_cols <- list(d1 = c(7:8),
                     e1 = c(12:14))

# Use the first classification of d1 for mutate and complete with all classifications
df %>% 
  mutate(!!names(missing_cols)[1] := missing_cols[[1]][1]) %>% 
  complete(nesting(a1, b1,c1), d1 = missing_cols[[1]])

期望的输出

df %>% 
  mutate(!!names(missing_cols)[1] := missing_cols[[1]][1]) %>% 
  mutate(!!names(missing_cols)[2] := missing_cols[[2]][1]) %>% 
  complete(nesting(a1, b1,c1), d1 = missing_cols[[1]], e1 = missing_cols[[2]])

这将获得 d1 的正确输出。如何对列表中的所有变量执行此操作?

标签: rdplyr

解决方案


我们可以crossing使用cross_df

library(tidyr)
crossing(df, cross_df(missing_cols))

#      a1    b1    c1    d1    e1
#   <int> <dbl> <int> <int> <int>
# 1     1     1     1     7    12
# 2     1     1     1     7    13
# 3     1     1     1     7    14
# 4     1     1     1     8    12
# 5     1     1     1     8    13
# 6     1     1     1     8    14
# 7     2     2     2     7    12
# 8     2     2     2     7    13
# 9     2     2     2     7    14
#10     2     2     2     8    12
# … with 26 more rows

cross_df创建所有可能的组合missing_colswhilecrossing获取该输出并创建所有可能的组合 with df


推荐阅读