假設我有一個資料框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))
我嘗試過濾滿足兩個條件的行(或條件,不是和):
type==2type==1和max(date)。
我的試用代碼:
df$date <- as.Date(df$date)
方法一:
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
方法二:
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
但它的作品時,我在代碼中使用geom_point(data=df[type==3 | date==max(df[type==2]$date)],size=2, aes(shape=type))從
我想知道如何使用上述兩種方法正確過濾?謝謝。
uj5u.com熱心網友回復:
請查看這是否會生成預期的輸出。
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 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/380662.html
下一篇:從串列R中呼叫索引案例
