picking a value from one column filters another column

Viewed 64

I am in the midst of dealing with a big data project where I want to filter one column from highlighting with another.

For example, I want to showcase house 1, and as a result of that, I want to compare House 1 with other values from other URBAN houses, not all houses.

table <- data.frame(
  house=paste("House", 1:15),
  category = c("Urban", "Rural", "Suburban")
)
table
#       house category
# 1   House 1    Urban
# 2   House 2    Rural
# 3   House 3 Suburban
# 4   House 4    Urban
# 5   House 5    Rural
# 6   House 6 Suburban
# 7   House 7    Urban
# 8   House 8    Rural
# 9   House 9 Suburban
# 10 House 10    Urban
# 11 House 11    Rural
# 12 House 12 Suburban
# 13 House 13    Urban
# 14 House 14    Rural
# 15 House 15 Suburban

I tried to give this a go, but it is not working for me...

table %>%
filter(house == house1) %>%
filter(category == table$house)

I want the output to look like this...

#      house category
# 1  House 1    Urban
# 2  House 4    Urban
# 3  House 7    Urban
# 4 House 10    Urban
# 5 House 13    Urban

Any suggestions are truly appreciated.

4 Answers

Maybe you can try the base R code below

subset(df,category == category[house=="House1"])

or dplyr option

df %>%
   filter(category == category[house == "House1"])

which gives

     house category
1   House1    Urban
3   House3    Urban
5   House5    Urban
12 House12    Urban
13 House13    Urban
14 House14    Urban

dummy data

df <- structure(list(house = c("House1", "House2", "House3", "House4", 
"House5", "House6", "House7", "House8", "House9", "House10",
"House11", "House12", "House13", "House14", "House15"), category = c("Urban", 
"Suburban", "Urban", "Rural", "Urban", "Suburban", "Suburban",
"Rural", "Rural", "Suburban", "Suburban", "Urban", "Urban", "Urban",
"Rural")), class = "data.frame", row.names = c(NA, -15L))

Using dplyr you might do something like this

table %>%
  filter(category == filter(table, house=="House 1") %>% pull(category))

Basically just a sub-query to find the category of House 1.

Try

table %>%
filter(category == "Urban")

Remember you need to use quotes " " in your filter statements.

You can also use match which will return index of first match and you can get corresponding category from it.

subset(table, category == category[match('House 1', house)])

      house category
1   House 1    Urban
4   House 4    Urban
7   House 7    Urban
10 House 10    Urban
13 House 13    Urban

Same code with filter if you want to use dplyr :

dplyr::filter(table, category == category[match('House 1', house)])
Related