根据两列和正在运行的ID过滤行

时间:2018-02-28 12:04:05

标签: r dplyr data.table tidyr

我需要根据第一个城市和位置名称基于两列限制数据。我想获得FirstPlace为1且第一个城市为伦敦的所有行。有关如何做到这一点的任何建议?在这种情况下,该示例应显示约翰的所有行,因为他在伦敦居住的第一年。

year <- c(2008, 2009, 2010, 2009, 2010, 2011)
person <- c('John', 'John', 'John', 'Brian', 'Brian','Vickey')
location <- c('London','Paris', 'Newyork','Paris','Paris','Miami')
df <- data.frame(year, person, location)

library(dplyr)
df %>% group_by(person) %>% mutate(FirstPlace = +(min(year) == year))

1 个答案:

答案 0 :(得分:3)

使用data.table

library(data.table)
setDT(df)[order(year), if(first(location) == 'London') .SD, by = person]

给出:

   person year location
1:   John 2008   London
2:   John 2009    Paris
3:   John 2010  Newyork

dplyr

library(dplyr)
df %>% 
  arrange(year) %>% 
  group_by(person) %>% 
  filter(first(location) == 'London')
相关问题