2017-03-13 2 views
1

다른 그룹 내에서 행을 필터링하려는 데이터 세트가 있습니다. I가 그룹을 필터링하는 그룹 내 fruit 최초로 출현을 사용하고자여러 조건을 기반으로 그룹 내에서 행 필터링

group = as.factor(c(1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3)) 
fruit = as.factor(c("apples", "apples", "apples", "oranges", 
        "oranges", "apples", "oranges", 
        "bananas", "bananas", "oranges", "bananas")) 
hit = c(1, 0, 1, 1, 
     0, 1, 1, 
     1, 0, 0, 1) 

dt = data.frame(group, fruit, hit) 
dt 
    group fruit hit 
     1 apples 1 
     1 apples 0 
     1 apples 1 
     1 oranges 1 
     2 oranges 0 
     2 apples 1 
     2 oranges 1 
     3 bananas 1 
     3 bananas 0 
     3 oranges 0 
     3 bananas 1 

:

이 dataframe 주어. 그러나 또 다른 조건이 있습니다. 나는 그 열매의 열을 계속 유지하고자합니다. hit1과 같습니다.

따라서 group 1의 경우 apples이 처음 발생하며 두 번 긍정적 인 히트가 있으므로이 두 행을 유지하려고합니다.

결과는 다음과 같습니다

group fruit hit 
    1 apples 1 
    1 apples 1 
    2 oranges 1 
    3 bananas 1 
    3 bananas 1 

을 당신이 dplyr으로 필터링 할 수 있습니다 알고 있지만 내가 이것을 달성 할 수 모르겠습니다.

+2

예, dplyr'이것을 달성 할 수있는 '과일'의 first 요소로 0 (&)가 '과일'과 동일하지 '(쉽게). 비 네트에서 한 번 살펴보면 다음과 같이 할 수 있습니다. https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html – ottlngr

+0

감사합니다. –

답변

1

dplyr을 사용할 수 있습니다. '그룹'으로 그룹화 한 후,이 filter 행은 '히트'

library(dplyr) 
dt %>% 
    group_by(group) %>% 
    filter(hit!=0 & fruit == first(fruit)) 
# group fruit hit 
# <fctr> <fctr> <dbl> 
#1  1 apples  1 
#2  1 apples  1 
#3  2 oranges  1 
#4  3 bananas  1 
#5  3 bananas  1 
관련 문제