1

I am using R and want to replace multiple values in data.frame starting with certain letters with one value.

For example below is the sample values in my data frame like XYZ1, XYZ2, XYZ3, XYZ4.. etc then i want to replace all values which starts with "XYZ" to "ABC"

Example

df is the data frame

 V1    V2   V3   V4 

XYZ1  XYZ2 XYZ4 XYZ10

XYZ3  RST1 WST3 XYZ11

Here (V1-V4) are the columns on which i want to replace all values which starts with "XYZ" change to "ABC".

Result i want is

df <-

V1   V2   V3   V4 

ABC  ABC  ABC  ABC

ABC  RST1  WST3  ABC

Individually i can do this by using == operator on each value in each column after converting them to character values, but how can i convert all values across multiple columns at once?

1
  • 1
    Have a look at sub(...) Commented Mar 13, 2018 at 14:42

2 Answers 2

1
library(dplyr)

df %>%
  mutate_all(funs(gsub("XYZ.*","ABC",.)))
  #mutate_at(vars(V1:V4), funs(gsub("XYZ.*","ABC",.)))
  

Output is:

   V1   V2   V3  V4
1 ABC  ABC  ABC ABC
2 ABC RST1 WST3 ABC

Sample data:

df <- structure(list(V1 = c("XYZ1", "XYZ3"), V2 = c("XYZ2", "RST1"), 
    V3 = c("XYZ4", "WST3"), V4 = c("XYZ10", "XYZ11")), .Names = c("V1", 
"V2", "V3", "V4"), class = "data.frame", row.names = c(NA, -2L
))
Sign up to request clarification or add additional context in comments.

Comments

0

Or using gsub

 a <- c("xyz1","xyz9")
    gsub("xyz",x=a,replacement="ABC",ignore.case = FALSE)

2 Comments

i have a lot of values to be replaced, so it will be tedious work to write down all values, can we do something so that we can select range of columns from where values should be replaced.
@AbhinavSharma gsub() is used to capture any certain pattern, in this case any value that contain "XYZ" , and replace that with replacement="ABC. The vector a was just an example I provided to show you how to use gsub. You can certainly use this function inside a loop or using dplyr's mutate as @Prem indicated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.