Jot eN
Jot eN

Reputation: 6416

Replace text or number after a colon in R

I have text file with many lines and I want to change (replace) the value (text or number), which is after colon. For example, I want to change one value (0.0000000) into another one; change a text into a value, and a text into a text. How to do that, while not messing the data structure in R?

I put my example data below. How to do that, while not messing the data structure in R? I've tried sub, but without any good results.

R Data:

text_data <- c("some parameter : 0.0000000", "another one    : none", "third one      : none")

Data:

some parameter : 0.0000000
another one    : none
third one      : none

Result:

some parameter : 7500.0000000
another one    : 0.0000000
third one      : "Missing Data"

Upvotes: 1

Views: 227

Answers (1)

nathanesau
nathanesau

Reputation: 1721

You can use the strsplit function.

text_data <- c("some parameter : 0.0000000", 
               "another one    : none", 
               "third one      : none")

stext <- strsplit(text_data, ":")
s1 <- lapply(stext, function(x) x[1])
s2 <- c("7500.0000000", 0.0000000, "Missing Data")

paste(s1, ":", s2)

# [1] "some parameter  : 7500.0000000"
# [2] "another one     : 0"           
# [3] "third one       : Missing Data"

Upvotes: 2

Related Questions