Search code examples
rif-statementdplyrpipe

Create a column with one of two variables based on another columns character


I have a dataframe that looks like this:

location sample_year mean
Ann Lake 2003 22
Bird Lake 2003 22
Tree Lake 2003 22
Ann River 2003 22
Tim River 2003 22
Dog River 2003 22
Apple River 2003 22

I want to create a new column specifying location type if its a river or lake:

location sample_year mean location_type
Ann Lake 2003 22 lake
Bird Lake 2003 22 lake
Tree Lake 2003 22 lake
Ann River 2003 22 river
Tim River 2003 22 river
Dog River 2003 22 river
Apple River 2003 22 river

I've tried this to no avail:

df%>%
  mutate(location_type = ifelse(location(contains("River"), "river", "lake")))

Is there a way to do this with a dplyr pipe?


Solution

  • you can use stringr's str_detect() function here.

    df <- df %>%
      mutate(location_type = ifelse(str_detect(location, "River"), "river", "lake"))