0

This may be a strange request, and there is not much I can do to actually show an example. Though I will try my hardest. Let's say I have an R script, such as a simple one that looks like this:

library(lubridate)
setwd("")
df=read.csv("...")
df=df[df$month != "" & !is.na(df$month),]
colnames(df)[3]="metric"

Is there now a way, to return a string which contains the actual text in my script? Or a creative way to save the information and read it back into the environment. For instance, I would like to create a string variable which is equal to:

"
library(lubridate)
setwd("")
df=read.csv("...")
df=df[df$month != "" & !is.na(df$month),]
colnames(df)[3]="metric""
Justin Klevs
  • 651
  • 6
  • 17
  • 5
    Not sure what you want, but assuming your script is already saved in a file, you can read it as text using `readLines('script.r')`. If you want to run the script inside another session without opening the file, you can use `source('script.r')`. – Carlos Eduardo Lagosta Aug 22 '18 at 01:59
  • Thanks! Simple solution that I should have known, but was helpful to do what I needed – Justin Klevs Aug 22 '18 at 14:14

1 Answers1

1

This just requires a quick google search.

Assuming that you have a text file named test.txt

tt <- readLines("test.txt")
gsub("\\\"","\'",tt)

Results:

> gsub("\\\"","\'",tt)
[1] "'"                                        
[2] "library(lubridate)"                       
[3] "setwd('')"                                
[4] "df=read.csv('...')"                       
[5] "df=df[df$month != '' & !is.na(df$month),]"
[6] "colnames(df)[3]='metric'"

But...

  • I changed "" to ''...for example look at setwd
  • I would be careful with the gsub part. By that I mean you have to be aware of what your text file contains. If a text file contains back slashes: "\\path\\to\\file" then the code will fail
MajesticKhan
  • 158
  • 1
  • 11