r - 如何按条件删除行
问题描述
我正在尝试删除条件不满足的行,例如。删除没有所有句点值的主题行是数据框
Subject Period
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
4 1
4 2
4 3
Subject Period
1 1
1 2
1 3
2 1
2 2
2 3
4 1
4 2
4 3
解决方案
A dplyr
solution.
library(dplyr)
dat %>%
group_by(Subject) %>%
filter(all(unique(dat$Period) %in% Period)) %>%
ungroup()
# # A tibble: 9 x 2
# Subject Period
# <int> <int>
# 1 1 1
# 2 1 2
# 3 1 3
# 4 2 1
# 5 2 2
# 6 2 3
# 7 4 1
# 8 4 2
# 9 4 3
A base R solution.
dat_list <- split(dat, f = dat$Subject)
keep_vec <- sapply(dat_list, function(x) all(unique(dat$Period) %in% x$Period))
dat_keep <- dat_list[keep_vec]
dat2 <- do.call(rbind, dat_keep)
dat2
# Subject Period
# 1.1 1 1
# 1.2 1 2
# 1.3 1 3
# 2.4 2 1
# 2.5 2 2
# 2.6 2 3
# 4.9 4 1
# 4.10 4 2
# 4.11 4 3
A solution using purrr
and dplyr
.
library(purrr)
library(dplyr)
dat2 <- dat %>%
split(f = .$Subject) %>%
keep(~all(unique(dat$Period) %in% .x$Period)) %>%
bind_rows()
dat2
# Subject Period
# 1 1 1
# 2 1 2
# 3 1 3
# 4 2 1
# 5 2 2
# 6 2 3
# 7 4 1
# 8 4 2
# 9 4 3
DATA
dat <- read.table(text = "Subject Period
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
4 1
4 2
4 3",
header = TRUE)
推荐阅读
- html - 如何制作响应式 HTML 按钮并将它们放在小分辨率上
- botframework - Bot Framework V4 上的语音服务身份验证问题
- angular - Anuglar - npm 审计修复 - 发生未处理的异常
- django - Django,对多个查询集进行分页
- azure - 使用 PowerShell 更改 Azure VM 的密码
- rust - 来自另一个字段的字段的结构生命周期
- android - 在我的 Android 应用程序中获取“原因:java.lang.RuntimeException”
- xml - Openssl asn1 编码例程问题 - 将 p7m 解密为 xml
- css - 为什么按钮没有得到我给它的颜色?
- html - 如何对齐项目中的项目