通过R中的两个条件过滤数据帧

时间:2018-09-06 20:58:16

标签: r dplyr

我有一个数据框,其中包含气候站给定年份中最高和最低的温度-All.Stations数据集:

Station.Name    Year    Month   Day TMAX    TMIN
GRAND MARAIS    1942    7       28    82      60
GRAND MARAIS    1962    3       17    42      22
LEECH LAKE      1956    7       3     72      50
ALBERT LEA 3 SE 1998    1       25    25      15
TWO HARBORS     1933    5       20    77      42
ARGYLE          1922    9       13    NA      NA

我还有一个按气候站分类的完整年份的数据框(即,这些年份是我一年中每天的数据所在的年份)-complete.years数据集:

Station.Name    Year
DULUTH          1904
AGASSIZ REFUGE  1995
LEECH LAKE      1956
GRAND MARAIS    1942
LEECH LAKE      1994

我想仅将第一个数据帧过滤为仅存在“站名”和“年份”并在第二个数据帧中匹配的数据。

正确的结果将是:

Station.Name    Year TMAX
GRAND MARAIS    1942   82
LEECH LAKE      1956   72

这就是我到目前为止使用dplyr所得到的:

Max.Tempurature <- All_Stations %>% 
  group_by(Station.Name, Year) %>%
  select(Station.Name, Year, TMAX) %>%
  filter(min_rank(desc(TMAX)) <= 1) %>%
  filter((Year %in% complete.years$Year & Station.Name %in% complete.years$Station.Name))

我可以按Year和Station.Name进行过滤,但这会在整个数据框中搜索匹配项。

如何按同一观测值中存在的Station.Name和Year进行过滤?

2 个答案:

答案 0 :(得分:2)

我们可以做一个import pandas as _pd

inner_join

数据

library(dplyr)
inner_join(All.Stations[c(1, 2, 5)], complete.years)
#   Station.Name Year TMAX
#1 GRAND MARAIS 1942   82
#2   LEECH LAKE 1956   72

答案 1 :(得分:1)

或与merge

cols <- c('Station.Name', 'Year', 'TMAX')
merge(All.Stations[cols], complete.years, all.x = FALSE)
#  Station.Name Year TMAX
#1 GRAND MARAIS 1942   82
#2   LEECH LAKE 1956   72

数据

All.Stations <- structure(list(Station.Name = c("GRAND MARAIS", "GRAND MARAIS", 
"LEECH LAKE", "ALBERT LEA 3 SE", "TWO HARBORS", "ARGYLE"), Year = c(1942L, 
1962L, 1956L, 1998L, 1933L, 1922L), Month = c(7L, 3L, 7L, 1L, 
5L, 9L), Day = c(28L, 17L, 3L, 25L, 20L, 13L), TMAX = c(82L, 
42L, 72L, 25L, 77L, NA), TMIN = c(60L, 22L, 50L, 15L, 42L, NA
)), .Names = c("Station.Name", "Year", "Month", "Day", "TMAX", 
"TMIN"), class = "data.frame", row.names = c(NA, -6L))

complete.years <- structure(list(Station.Name = c("DULUTH", "AGASSIZ REFUGE", "LEECH LAKE", 
"GRAND MARAIS", "LEECH LAKE"), Year = c(1904L, 1995L, 1956L, 
1942L, 1994L)), .Names = c("Station.Name", "Year"), class = "data.frame", row.names = c(NA, 
-5L))