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?
CodePudding user response:
We may use a logical condition in ifelse/case_when
to paste
the *
for those values in 'factors' correspond to 'indicator' value of 1
library(dplyr)
library(stringr)
data %>%
mutate(factors = case_when(indicator == 1 ~
str_c(as.character(factors), "*"), TRUE ~ as.character(factors)))
-output
# A tibble: 4 x 2
factors indicator
<chr> <chr>
1 a* 1
2 b 0
3 c* 1
4 d 0
CodePudding user response:
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