Home > Enterprise >  How do I change the value of one variable based on the value of another variable?
How do I change the value of one variable based on the value of another variable?

Time:02-26

I have two variables. One categorical one with labels that take values 1-7. The value 7 indicates "other" The other variable is the text that represents that "other".

col1  col2
1     
3
6
2
7     "some text"
7     "some text"
2
7     "some other text"
7     "some third text"
7     "Some thrid Text"

I want to change the value in col1 based on the value in col2. So for example

IF col2 = "some text", col1 = 2 (and it deletes the "some text" in col2)
IF col2 = "some other text", col1 = 4 (and it deletes the "some other text in col2)
IF col2 = "Some thrid Text", col2 = "some third text"

col1  col2
1     
3
6
2
2     
2     
2
4     
7     "some third text"
7     "some third Text"

Side note: col1 has value labels on it's values 1-7 and I don't want to mess with that.

CodePudding user response:

df %>%
  mutate(col1 = coalesce(case_when(col2 == 'some text' ~ 2,
                                   col2 == 'some other text' ~ 4), col1),
         col2 = str_remove(col2, 'some (other )?text'))
   col1            col2
1     1                
2     3                
3     6                
4     2                
5     2                
6     2                
7     2                
8     4                
9     7 some third text
10    7 Some thrid Text
  • Related