Problem Using Filter

I am trying to run this code:

     onlineta_city_hotels <- filter(hotel_bookings, 
                       (hotel=="City Hotel" & 
                         hotel_bookings$market_segment=="Online TA"))

but it gives this error:

       Error in filter(hotel_bookings, (hotel == "City Hotel" & hotel_bookings$market_segment ==  : 

object 'hotel' not found

I got the code from a coursera course and don't know how to make it work. Any help would be greatly appreciated.
N.B. It was not an exam question, just a practice activity, thanks!

1 Like

Hi @Elie_Tondreau , check this example for make a filter with dplyr:

library(dplyr)
onlineta_city_hotels %>% 
  select(hotel , market_segment)  %>%
  filter(hotel == "City Hotel" & market_segment == "Online TA")

The help could be better if you put a reproducible example of data:

When getting an "object not found" error, the first thing to check if it exists. For a data frame, colnames does this

colnames(hotel_bookings)

and check for the variables hotel and market_segment. If they are, then the cause is probably that the dplyr library hasn't been loaded. Two ways to fix. Simplest

library(dplyr)

Alternatively,

dplyr::filter(hotel_bookings ...

There is a filter function in the {stats} library, which is loaded by default, so it's necessary to tell the script which to use. library(dplyr) does this by masking the {stats} function. dplyr::filter specifies the version to use.

When using {dplyr}, I prefer to write it left-to-right, starting with the data frame used as the input and ending up with the assignment to the new object

hotel_bookings %>% filter(hotel == "City Hotel" & market_segment == "Online TA")  -> onlineta_city_hotels

but usually you see

onlineta_city_hotels <- hotel_bookings %>% filter(hotel == "City Hotel" & market_segment == "Online TA")  

Two other ways to do the same are worth knowing about.

mtcars[mtcars$mpg > 20 & mtcars$cyl == 6,] 
#>                 mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4      21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag  21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1

library(data.table)
mt <- data.table(mtcars, keep.rownames = TRUE)
mt[mpg > 20 & cyl == 6]
#>                rn  mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> 1:      Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> 2:  Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> 3: Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.