1

I've been trying to replace multiple strings in a column of a data frame in R using str_replace_all.

Currently I've written up something simple for now (below)

mydata$Final_Result <- str_replace_all(mydata$Final_Result, 'Absent', 'A')
mydata$Final_Result <- str_replace_all(mydata$Final_Result, 'Present', 'P')

I have other strings to replace in the same column. So I am looking for a more elegant way to write this code in a single line.

Would appreciate if anyone could advise on how this can be done.

www
  • 38,575
  • 12
  • 48
  • 84
Arun Mahadevan
  • 21
  • 1
  • 1
  • 3
  • I did. I was in the middle of editing the banner. Someone else reopened. See the question timeline. – M-- Feb 20 '20 at 13:47

2 Answers2

9

You can do the following to add as many pattern-replacement pairs as you want in one line.

library(stringr)

vec <- c("Absent", "Absent", "Present", "Present", "XX", "YY", "ZZ")

str_replace_all(vec, c("Absent" = "A", "Present" = "P"))
# [1] "A"  "A"  "P"  "P"  "XX" "YY" "ZZ"
www
  • 38,575
  • 12
  • 48
  • 84
2

You could use case_when from the dplyr package:

mydata$Final_Result <- case_when(
    mydata$Final_Result == "Absent" ~ "A",
    mydata$Final_Result == "Present" ~ "P",
    TRUE ~ NA
)

case_when has one potential advantage over str_replace_all in that it allows for a default catch all replacement.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360