Replace some numeric value after a pattern in a string of txt in R (grep?) -
i have several txt files input file model, need change of model parameters in order conduct experiments. however, there many parameters , changing them hand time consuming. thought using readlines() , {grep} in r search , replace parameter values not successful, hope me. thank you.
the file has lines this:
bubbling pressure 1 = 0.3389 .4423 .4118 field capacity 1 = 0.35 0.38 0.37 wilting point 1 = 0.13 0.14 0.13 bulk density 1 = 750. 1400. 1500. vertical conductivity 1 = 2.904e-06 3.63e-05 3.63e-05 ..... bubbling pressure 3 = 0.2044 0.2876 0.2876 field capacity 3 = 0.31 0.33 0.33 wilting point 3 = 0.13 0.14 0.14 bulk density 3 = 750. 1400. 1500. vertical conductivity 3 = 3.16e-06 3.95e-05 3.95e-05 ...
i want double vertical conductivity parameters...but not sure how isolate numbers in scientific notation (such "3.16e-06").
is there way isolate each 1 of number in lines contain pattern "vertical conductivity"
vertical conductivity 3 = 3.16e-06 3.95e-05 3.95e-05
and double each 1 of numbers?
vertical conductivity 3 = 6.32e-06 7.90e-05 7.90e-05
i have manage use grep isolate each line of text contains pattern "vertical conductivity" not sure how numerical values out...
thanks, nick
we can gsubfn
without changing original structure , modify op may or may not wanted.
here, reading dataset using readlines
, index of 'lines' has 'vertical conductivity' substring grepl
('i1'). then, use gsubfn
replace values double of that.
library(gsubfn) i1 <- grepl("vertical conductivity", lines) lines[i1] <- gsubfn("[0-9.]+e[-+][0-9]+", ~format(as.numeric(x)*2, scientific = true), lines[i1]) lines #[1] "bubbling pressure 1 = 0.3389 .4423 .4118" #[2] "field capacity 1 = 0.35 0.38 0.37" #[3] "wilting point 1 = 0.13 0.14 0.13" #[4] "bulk density 1 = 750. 1400. 1500." #[5] "vertical conductivity 1 = 5.808e-06 7.26e-05 7.26e-05" #[6] "bubbling pressure 3 = 0.2044 0.2876 0.2876" #[7] "field capacity 3 = 0.31 0.33 0.33" #[8] "wilting point 3 = 0.13 0.14 0.14" #[9] "bulk density 3 = 750. 1400. 1500." #[10] "vertical conductivity 3 = 6.32e-06 7.9e-05 7.9e-05"
data
lines <- trimws(readlines(textconnection( 'bubbling pressure 1 = 0.3389 .4423 .4118 field capacity 1 = 0.35 0.38 0.37 wilting point 1 = 0.13 0.14 0.13 bulk density 1 = 750. 1400. 1500. vertical conductivity 1 = 2.904e-06 3.63e-05 3.63e-05 bubbling pressure 3 = 0.2044 0.2876 0.2876 field capacity 3 = 0.31 0.33 0.33 wilting point 3 = 0.13 0.14 0.14 bulk density 3 = 750. 1400. 1500. vertical conductivity 3 = 3.16e-06 3.95e-05 3.95e-05')))
we can directly read file
lines <- readlines("yourfile.txt")
Comments
Post a Comment