r - 从列表中填充 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 的正确输出。如何对列表中的所有变量执行此操作?
解决方案
我们可以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_cols
whilecrossing
获取该输出并创建所有可能的组合 with df
。
推荐阅读
- reactjs - ReactJS - 大型视频文件使计算机在 npm 启动后冻结
- regex - PowerShell - 在替换期间在字符串中插入换行符
- iis - ECP 和 OWA 不工作 - “用户名/密码不正确”
- mysql - 如何按组从mysql中获取下一行/上一行
- html -
html标签的空href是什么意思? - jmeter - 如何解决错误:java.net.ConnectException:连接超时:在 jmeter 中连接
- keras - keras 模型:输入和输出配置
- javascript - 剑道 mvc 命令自定义不起作用
- javascript - Mapbox GL JS:如何在地图边缘定位刻度标签?
- node.js - NodeJs FindOne 返回未定义