1

I have an R script with several functions I made for multiple projects I have going on. There are also about 40 vectors of characters in this same script. The vectors contain key words I am looking for in different Twitter posts, and the function creates a dummy variable to identify if the posts contain those key words.

When I want to use the functions, I call source("myScript.R") to use those functions, but this also fills my environment with the 40 vectors, which I don't necessarily want to have happen.

Is there a way to mask the vectors so that when I run source (or some other call) then I will only see the functions in my environment and not the vectors?

Jacob
  • 406
  • 3
  • 19
  • 3
    You should consider creating a package (instead of a script). That would be the neatest way to load your functions. Packages are not just to publish and share :) – prosoitos Oct 22 '19 at 14:02
  • As a very simple solution, is writing a script with only your functions not an option? – prosoitos Oct 22 '19 at 14:06
  • No, the vectors are essentially dictionaries with sets of words to look for. For example, one of the functions loops through my data using ```str_detect``` to find the words within each dictionary, and creates different dummy variables in the df depending on which dictionary being used. – Jacob Oct 22 '19 at 14:12
  • Creating a package might be the best option then. Or you could also remove the vectors from your environment after loading the script. But that is not exactly a neat workflow... – prosoitos Oct 22 '19 at 14:15
  • Do your functions still work if your vectors are not in the global environment? (the vectors may only be necessary to create the functions, but maybe they are also needed to run the functions) – prosoitos Oct 22 '19 at 14:17
  • 1
    No, they don't. I'll definitely take a look at creating a package though! – Jacob Oct 22 '19 at 14:18
  • In general you want to separate data from code. You can either move your code into a package, or just separate the data vectors and functions into different script files that you can source independently. In R, there is very little difference between a function and a value since R is a proper functional language. They are both just objects to R. – MrFlick Oct 22 '19 at 14:44
  • @MrFlick I ended up just making a package and it answered my question. I didn't want to separate the vectors from the functions because they are standard vectors that I wont be changing but will be applicable in multiple projects – Jacob Oct 22 '19 at 17:11

1 Answers1

0

Per @prosoitos 's comment above, I made a package with the R script containing my code and it worked like a charm

Jacob
  • 406
  • 3
  • 19