Add a new column based on string value from an existing column in Rstudio

Viewed 1582

I have a data set in R containing multiple columns. One column room_type contains either the string values Entire home/apt or Shared room or Private room or it's blank. I want to create a new column room_type_new where string values are based on the column room_type. Note: There are over 100 000 rows in the data set.

See below:

room_type          room_type_new
Entire home/apt    Entire home
Private room       Shared home
Shared room        Shared home
NA                 NULL

I tried this code, which prints the correct output but doesn't pass the new values to room_type_new:

data1$room_type <- as.character(data1$room_type)
data1$room_type_new <- NA
data1$room_type_new <- as.character(data1$room_type_new)

    data1%>%
      mutate(room_type_new = case_when(.$room_type %in% c("Entire home/apt") ~ "Entire home",.$room_type %in% c("Private room", "Shared room") ~ "Shared home")
2 Answers

Here is an option with case_when

library(dplyr)
library(stringr)
df1 %>%
   mutate(room_type_new = case_when(str_detect(room_type, "Entire") ~ 
     'Entire home', is.na(room_type) ~ NA_character_, TRUE ~ "Shared home"))

Build df:

df <- data.frame(room_type = as.character(c("Entire home/apt", "Private room", "Shared room")), stringsAsFactors = F)

Base R one liner assuming only two unique values for df$room_type_new:

df$room_type_new <- ifelse(grepl("Entire home/apt", df$room_type), "Entire home", "Shared home")

Base R one liner if > 2 unique values for df$room_type_new, nest the ifelse:

df$room_type_new <- ifelse(grepl("Entire home/apt", df$room_type), "Entire home", ifelse(grepl("Private room|Shared room", df$room_type), "Shared home", "")

Also the reason why your output is being passed to anything is because your not assigning the result to an object -- using your code:

data1 <- 
 data1%>%
  mutate(room_type_new = case_when(.$room_type %in% c("Entire home/apt") ~ "Entire home",.$room_type %in% c("Private room", "Shared room") ~ "Shared home")
Related