Some data:
x <- structure(list(X. = c("4,084", "4,084", "4,084", "4,084", "4,084"
), ADR = c("1,099.69", "68.66", "232.72", "195.66", "98"), hotel_id = c("2,313,076",
"583,666", "1,251,372", "1,545,890", "298,160"), city_id = c("9,395",
"17,193", "5,085", "16,808", "8,584"), star_rating = c(5, 2,
3, 4, 4), accommodation_type_name = c("Hotel", "Bungalow", "Hotel",
"Hotel", "Hotel"), chain_hotel = c("chain", "non-chain", "non-chain",
"non-chain", "non-chain"), booking_date = c("10/5/2016", "12/4/2016",
"11/6/2016", "10/22/2016", "12/11/2016"), checkin_date = c("10/27/2016",
"12/9/2016", "11/18/2016", "11/3/2016", "12/11/2016"), checkout_date = c("10/30/2016",
"12/12/2016", "11/20/2016", "11/4/2016", "12/12/2016"), city = c("A",
"B", "C", "D", "E")), class = "data.frame", row.names = c(NA,
-5L), .Names = c("X.", "ADR", "hotel_id", "city_id", "star_rating",
"accommodation_type_name", "chain_hotel", "booking_date", "checkin_date",
"checkout_date", "city"))
Looks like this:
> glimpse(x)
Observations: 27,298
Variables: 11
$ X. <chr> "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"...
$ ADR <chr> "71.06", "76.56", "153.88", "126.6", "115.08", "81.6", "77.16", "168.36",...
$ hotel_id <chr> "297,388", "298,322", "2,313,076", "2,240,838", "2,240,838", "331,350", "...
$ city_id <chr> "9,395", "9,395", "9,395", "9,395", "9,395", "9,395", "9,395", "9,395", "...
$ star_rating <dbl> 2.5, 3.0, 5.0, 3.5, 3.5, 3.0, 3.0, 5.0, 2.0, 3.0, 4.0, 2.0, 3.0, 2.0, 3.0...
$ accommadation_type_name <chr> "Hotel", "Hotel", "Hotel", "Hotel", "Hotel", "Hotel", "Hotel", "Hotel", "...
$ chain_hotel <chr> "non-chain", "non-chain", "chain", "non-chain", "non-chain", "non-chain",...
$ booking_date <chr> "8/2/2016", "8/2/2016", "8/2/2016", "8/4/2016", "8/4/2016", "8/4/2016", "...
$ checkin_date <chr> "10/1/2016", "10/1/2016", "10/1/2016", "10/2/2016", "10/2/2016", "10/3/20...
$ checkout_date <chr> "10/2/2016", "10/2/2016", "10/2/2016", "10/3/2016", "10/3/2016", "10/5/20...
$ city <chr> "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A"...
I wouldlike to mutate columns ADR: star_rating. Specifically I want to gsub out any commas.
I tried:
x <- x %>%
mutate_each(ADR:star_rating, funs(gsub ",", ""))
But this throws an error:
Error: unexpected string constant in:
"x <- x %>%
mutate_each(ADR:star_rating, funs(gsub ",""
In base r I could d this:
vars <- c("ADR", "hotel_id", "city_id", "star_rating")
x[vars] <- lapply(x[vars], function(i) gsub(",", "", i))
However, if I could do this within a dplyr chain it would be convenient and mean I don;t have to write out each variable like I do when declaring vars, I could just use ADR:star_rating.
How can I achieve this in dplyr with mutate?
See Question&Answers more detail:
os