0

Given a dataframe as follows:

  city type  count
0   bj    a     10
1   bj    a     23
2   bj    b     12
3   bj    c     34
4   sh    a     17
5   sh    b     18
6   sh    c     25
7   sh    c     13
8   sh    a     12

I want to filter rows based on city and type: bj-a, bj-c, sh-b, the expected result will like this:

  city type  count
0   bj    a     10
1   bj    a     23
2   bj    c     34
3   sh    b     18

How can I do that in R? Thanks.

2 Answers 2

3

You can do that using subset :

subset(df, city == 'bj' & type %in% c('a', 'c') | city == 'sh' & type == 'b')

#  city type count
#0   bj    a    10
#1   bj    a    23
#3   bj    c    34
#5   sh    b    18

Or filter in dplyr :

library(dplyr)
df %>%
  filter(city == 'bj' & type %in% c('a', 'c') | 
         city == 'sh' & type == 'b')
Sign up to request clarification or add additional context in comments.

Comments

1

For a base R option, you could subset using direct bracket notation:

df[(df$city == "bj" & df$type %in% c("a", "c")) |
   (df$city == "sh" & df$type == "b"), ]

  city type count
1   bj    a    10
2   bj    a    23
4   bj    c    34
6   sh    b    18

Data:

df <- data.frame(city=c("bj", "bj", "bj", "bj", "sh", "sh", "sh", "sh", "sh" ),
                 type=c("a", "a", "b", "c", "a", "b", "c", "c", "a"),
                 count=c(10, 23, 12, 34, 17, 18, 25, 13, 12), stringsAsFactors=FALSE)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.