Henk Straten
Henk Straten

Reputation: 1445

Replace values in a .txt value

I have a dataset that looks like this:

B1,F1,D1,B0 B0  D1  F1  B1  B1,A1,E1    C#2 B1,G1,E1    B1,G1,E1    C#2,A1,E1   B1,G1,E1    B1  E2  B1,F1,D1    B1,D1,B0    B1,D1,B0    A1  F1  D1  G1,E1,B0    G1  G1  G1  E1  G1
B-1 A-1 G-1 G-1 F-1 E-1 B-1 B-1 B-1 E-1

What I would like to now is to read in the values and then replace specific values.

So the pseudo code is:

#Read in data
#For line in data:
 #Split words
  #if word contains value from list (fe C,D)
   #Replace it by X

So if my list is

list_replace = c("B", "F")

My expected output is:

X1,F1,D1,X0 X0  D1  X1  X1  X1,A1,E1    C#2 X1,G1,E1    X1,G1,E1    
C#2,A1,E1   X1,G1,E1    X1  E2  X1,X1,D1    B1,D1,B0    X1,D1,X0    A1  X1  
D1  G1,E1,X0    G1  G1  G1  E1  G1

X-1 A-1 G-1 G-1 X-1 E-1 X-1 X-1 X-1 E-1

I created the following code:

#Read in datea
data <-read.table("sample.txt", header = FALSE)
for i in 1:nrow(data){
  words = strsplit(data[i]
  for word 1:length(words){
   #Replace values
 }
}

However now I only gets the first value of my to_be_replaced list. Any suggestion on how i can replace everything... And the preferably edit it right away in the .txt file.

Upvotes: 0

Views: 51

Answers (1)

Carl Boneri
Carl Boneri

Reputation: 2722

I am unsure of that data structure you show as the sample, but here's a function that should do the trick.

It will use gsub from the base packages and a regex pattern to find the characters of interest, and allow a variable input that will replace all matches to the pattern with a given value.

 fn <- function(find = NULL, replace = "X"){
    raw_string <- readLines("sample.txt")
    sub_pat <- sprintf("(%s)", paste0(find, collapse = "|"))
    gsub(sub_pat, replace, raw_string)
}

So for the patterns(letters) B, E, G

fn(find = c("B", "E", "G"), replace = "XX")

[1] "XX1,F1,D1,XX0 XX0 D1 F1 XX1 XX1,A1,XX1 C#2 XX1,XX1,XX1 XX1,
     XX1,XX1 C#2,A1,XX1 XX1,XX1,XX1 XX1 XX2 XX1,F1,D1
     XX1,D1,XX0 XX1,D1,XX0 A1 F1 D1 XX1,XX1,XX0 XX1 XX1 XX1 XX1
     XX1"
[2] "XX-1 A-1 XX-1 XX-1 F-1 XX-1 XX-1 XX-1 XX-1 XX-1"

Upvotes: 1

Related Questions