Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

r - Use loop to replace word and run multiple lines

I have the word "JAN" in many lines. Here is an example:

OccRateJAN_Yuki<-YukiJANoccupied/31

I want to use loop so that each time "JAN" is in a line, replace it with "FEB" and run the whole thing. Then change every "JAN" to "MAR" and run the whole thing... Until "DEC" and then end the statement.

Is it possible to search for the word "JAN" through all the lines of code, replace the word and run? How could I write the code?

Thanks in advance.

question from:https://stackoverflow.com/questions/65929255/use-loop-to-replace-word-and-run-multiple-lines

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're running an R script from bash, you can loop over it with:

array=(JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC)
for f in {0..11}
  do sed "s/JAN/"${array[f]}"/g" script.R > script_"$f".R
  Rscript --vanilla script_"$f".R
done

This keeps each individual script (one per month named script_0.R / script_1.R / etc) in case a run fails and you need to rerun it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...