Home > Enterprise >  Insert value in a column if value in another column contains a certain word/letter
Insert value in a column if value in another column contains a certain word/letter

Time:10-13

I am essentially trying to create some code to detect if the values in a column contains "%". If so, make df$unit col to be %. if not so, do nothing.

I tried the below code but it returns % for all rows of values, even if they don't contain % inside.

How should I fix it?

if(stringr::str_detect(df$variable, "%")) {
        
        df$unit <- "%"
        
      }

CodePudding user response:

A tidyverse approach

library(dplyr)
library(stringr)

df %>% 
  mutate(unit = if_else(str_detect(variable,"%"),"%",unit))

CodePudding user response:

Try the below:

library(stringr)

df[str_detect(df$variable, "%"), 'unit'] <- "%"

This doesn't need any extra libraries.

CodePudding user response:

In base R, you can use replace with grepl.

df <- transform(df,unit = replace(unit, grepl('%', variable, fixed = TRUE), '%'))

Or

df$unit[grepl('%', df$variable, fixed = TRUE)] <- '%'
  •  Tags:  
  • r
  • Related