Abhinav Sharma
Abhinav Sharma

Reputation: 45

R - Replace multiple values in data.frame with one value

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?

Upvotes: 1

Views: 3482

Answers (2)

Prem
Prem

Reputation: 11955

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
))

Upvotes: 1

lemonC
lemonC

Reputation: 78

Or using gsub

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

Upvotes: 0

Related Questions