假设我有一个数据df,如下所示:
df <- structure(list(date = c("2021-10-1", "2021-10-2", "2021-10-3",
"2021-10-4", "2021-10-5", "2021-10-6", "2021-10-7", "2021-10-8",
"2021-10-9"), value = c(190.3, 174.9, 163.2, 168.4, 168.6, 168.2,
163.5, 161.6, 172.9), type = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L)), class = "data.frame", row.names = c(NA, -9L))我试图筛选满足两个条件的行(或 condtions,而不是和):
type==2type==1和max(date).我的试用码:
df$date <- as.Date(df$date)方法1:
df[type==2 | date==max(df[type==1]$date)]退出:
Error in `[.data.frame`(df, type == 2 | date == max(df[type == 1]$date)) :
object 'type' not found方法2:
df %>%
filter(type==2|date==max(df[type==1]$date))退出:
Error: Problem with `filter()` input `..1`.
i Input `..1` is `type == 3 | date == max(df[type == 2]$date)`.
x undefined columns selected但是,当我在来自this link的代码this link中使用它时,它就会产生效果。
预期结果:

我想知道如何使用上述两种方法正确地进行过滤?谢谢。
发布于 2021-12-14 08:46:27
请查看这是否生成预期的输出。
library(dplyr)
df2 <- df %>%
mutate(date = as.Date(date)) %>%
filter(type == 2 | (type == 1 & date == max(date[type == 1])))
df2
# date value type
# 1 2021-10-05 168.6 1
# 2 2021-10-06 168.2 2
# 3 2021-10-07 163.5 2
# 4 2021-10-08 161.6 2
# 5 2021-10-09 172.9 2https://stackoverflow.com/questions/70345961
复制相似问题