Home > Software design >  conditionally rename variable by using dplyr
conditionally rename variable by using dplyr

Time:06-13

The question is as follows:

Create a new variable that assumes the value 1 when the house type is House, 2 if the type is Penthouse, 3 if the type is Flat / Apartment or Studio and 0 otherwise. Use the table() function on the new variable.

the variables House type consists of the following unique values: "House", "Flat/Apartment", "new development", "duplex", "Penthouse", "studio", "bungalow", "Mews".

Does anyone now which dplyr function I need to solve this question?

CodePudding user response:

You can use case_when(), followed by count()

df %>%
  mutate(new_var = case_when(
    House=="House"~1,
    House=="Penthouse"~2,
    House %in% c("Flat/Apartment","Studio")~3,
    TRUE~0)) %>%
  count(new_var)

CodePudding user response:

It may be easier with factor and levels specified

v1 <- with(df, as.integer(factor(House, levels = c("House", 
                "Penthouse", "Flat/Apartment", "Studio"))))
v1[is.na(v1)] <- 0
v1[v1 == 4] <- 3
table(v1)
  • Related