Search code examples
rif-statementmathdataframearithmetic-expressions

In an R dataframe, if I want to change a column value to another value, but only if it equals 3 different things


I have a data frame in R called QCEW_County_Denominated. In this data frame I have a column called Industry. Whenever the value of this column is [31-33], [44-45], or [48-49] - actual values - not value ranges, I would like to change the value to 31, 44, and 48 respectively. Any advice on how to format this? If-then statements in R are my weakest point so I figured I'd ask here.


Solution

  • check out case_when()

    library('dplyr')
    x <- data.frame(industry = rep(c("[31-33]","[44-45]","[48-49]"), each = 4))
    x %>% 
     mutate(industry_n = case_when(.$industry == "[31-33]" ~ 31, 
                                   .$industry == "[44-45]" ~ 44, 
                                   .$industry == "[48-49]" ~ 48))
    

    or if you have the dev version of dplyr (devtools::install_github("hadley/dplyr"), you can run:

    x %>% 
     mutate(industry_n = case_when(industry == "[31-33]" ~ 31, 
                                   industry == "[44-45]" ~ 44, 
                                   industry == "[48-49]" ~ 48))