假設我有一個資料集:
Name <- c("Jon", "Bill", "Maria", "Ben", "Tina")
Age <- c(23, 41, 32, 58, 26)
datesurg<-c("2022-03-17","2022-02-20","2022-01-23","2022-03-18","2022-04-17")
dateevent<-c("2022-03-20","2022-02-21","2022-03-17","2022-03-18","2022-04-17")
datelookup<-c("2022-03-20","2022-02-20","2022-01-23","2022-03-18","2022-04-17")
df <- data.frame(Name, Age,datesurg,dateevent,datelookup)
我想要一個資料框,如果此變數與“datelookup”列中的任何日期匹配,則對于“datesurg”的每一行,保留該行。
Name Age datesurg dateevent datelookup
2 Bill 41 2022-02-20 2022-02-21 2022-02-20
3 Maria 32 2022-01-23 2022-03-17 2022-01-23
4 Ben 58 2022-03-18 2022-03-18 2022-03-18
5 Tina 26 2022-04-17 2022-04-17 2022-04-17
接下來我想保留“datesurg”或“dateevent”等于“datelookup”的行。
Name Age datesurg dateevent datelookup
1 Jon 23 2022-03-17 2022-03-20 2022-03-20
2 Bill 41 2022-02-20 2022-02-21 2022-02-20
3 Maria 32 2022-01-23 2022-03-17 2022-01-23
4 Ben 58 2022-03-18 2022-03-18 2022-03-18
5 Tina 26 2022-04-17 2022-04-17 2022-04-17
uj5u.com熱心網友回復:
我們可以用if_any
library(dplyr)
library(lubridate)
df %>%
mutate(across(starts_with('date'), ymd)) %>%
filter(if_any(dateevent:datelookup, ~ datesurg == .x))
-輸出
Name Age datesurg dateevent datelookup
1 Bill 41 2022-02-20 2022-02-21 2022-02-20
2 Maria 32 2022-01-23 2022-03-17 2022-01-23
3 Ben 58 2022-03-18 2022-03-18 2022-03-18
4 Tina 26 2022-04-17 2022-04-17 2022-04-17
或者對于第二種情況
df %>%
mutate(across(starts_with('date'), ymd)) %>%
filter(if_any(c(datesurg, dateevent), ~ datelookup == .x))
-輸出
Name Age datesurg dateevent datelookup
1 Jon 23 2022-03-17 2022-03-20 2022-03-20
2 Bill 41 2022-02-20 2022-02-21 2022-02-20
3 Maria 32 2022-01-23 2022-03-17 2022-01-23
4 Ben 58 2022-03-18 2022-03-18 2022-03-18
5 Tina 26 2022-04-17 2022-04-17 2022-04-17
uj5u.com熱心網友回復:
也許用base R試試這個
“datelookup”中的“datesurg”
df[with(df, datesurg %in% datelookup), ]
Name Age datesurg dateevent datelookup
2 Bill 41 2022-02-20 2022-02-21 2022-02-20
3 Maria 32 2022-01-23 2022-03-17 2022-01-23
4 Ben 58 2022-03-18 2022-03-18 2022-03-18
5 Tina 26 2022-04-17 2022-04-17 2022-04-17
“datelookup”中的“datesurg”或“dateevent”
df[with(df, datesurg %in% datelookup | dateevent %in% datelookup), ]
Name Age datesurg dateevent datelookup
1 Jon 23 2022-03-17 2022-03-20 2022-03-20
2 Bill 41 2022-02-20 2022-02-21 2022-02-20
3 Maria 32 2022-01-23 2022-03-17 2022-01-23
4 Ben 58 2022-03-18 2022-03-18 2022-03-18
5 Tina 26 2022-04-17 2022-04-17 2022-04-17
uj5u.com熱心網友回復:
我們可以這樣做:
library(dplyr)
#1
df_surg <- df %>%
filter(datesurg %in% datelookup)
#2
df_surg_event <- df %>%
filter(datesurg == datelookup | dateevent == datelookup)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/520921.html
標籤:r数据框数据操作
下一篇:查找組內上一個冬天的事件數
