title: determine which packages are used
body: <p>Is there a quick way to scan an R script and determine which packages are actually used? By this I mean looking at all of the functions called in the script and returning a list of packages that contain these function names? (I know that function names are not exclusive to any one package)</p>
  
  <p>Why not just look at packages called by <code>library()</code> or <code>require()</code>? Right. Well, I have a bad habit of loading packages I often use regardless of whether I actually use them in the script. </p>
  
  <p>I'd like to clean up some scripts that I intend to share with others by removing unused packages.</p>
  
  <p>I resolve to change my ways in 2016. Please help me get started.</p>
  
  <p><strong>Update</strong></p>
  
  <p>Some good ideas in the comments...</p>
  
  <pre><code># create an R file that uses a few functions
  
  fileConn&lt;-file("test.R")
  writeLines(c("df &lt;- data.frame(v1=c(1, 1, 1), v2=c(1, 2, 3))",
               "\n",
               "m &lt;- mean(df$v2)",
               "\n",
               "describe(df)  #psych package"),
             fileConn)
  close(fileConn)
  
  # getParseData approach
  pkg &lt;- getParseData(parse("test.R"))
  pkg &lt;- pkg[pkg$token=="SYMBOL_FUNCTION_CALL",]
  pkg &lt;- pkg[!duplicated(pkg$text),]
  pkgname &lt;- pkg$text
  pkgname
  # [1] "data.frame" "c"          "mean"       "describe" 
  </code></pre>
  
  <p><strong>Update 2</strong></p>
  
  <p>An ugly attempt to implement @nicola's idea:</p>
  
  <pre><code># load all probable packages first
  pkgList &lt;- list(pkgname)
  for (i in 1:length(pkgname)) {
    try(print(packageName(environment(get(pkgList[[1]][i])))))
  }
  </code></pre>
  
  <p>It does not like the <code>c()</code> function, but the results seem otherwise correct. </p>
  
  <pre><code>#[1] "base"
  #Error in packageName(environment(get(pkgList[[1]][i]))) : 
  #  'env' must be an environment
  #[1] "base"
  #[1] "psych"
  </code></pre>