Search code examples
rfactors

r: add "*" to factor level if indicator variable is 1


I have something like the below data setup.

library(tidyverse)  
library(dplyr)


factors <- c("a","b","c","d")
indicator=c(1,0,1,0)
data <- as_tibble(cbind(factors,indicator))
data$factors <- as.factor(data$factors)

I would like to append an asterisk to the factor level for all rows for which the indicator variable is equal to 1. The value of the indicator does not ever vary within a given value of the factor. That is, for all observations for which the factor is equal to "a" the indicator is always 1.

# A tibble: 4 x 2
  factors indicator
  <chr>   <chr>    
1 a*      1        
2 b       0        
3 c*      1        
4 d       0        

What's the best way to do this?


Solution

  • This should work:

    data %>%
      mutate(factors = ifelse(indicator==1, paste0(factors, "*"), factors))
    # A tibble: 4 x 2
      factors indicator
      <chr>   <chr>    
    1 a*      1        
    2 2       0        
    3 c*      1        
    4 4       0