Skip to contents

A setwd() call in analysis code is a portability problem: it hardcodes an assumption about the working directory the code runs in (frequently an absolute path on the author's own machine), mutates global state, and makes a script depend on being run from a particular place. Best practice is to keep the working directory as the caller sets it and use relative paths. This scans the (comment-free) code for setwd(...) calls and returns one row per call, with the argument as written. R-only (the construct is R's; other languages have their own, e.g. Stata cd, which this does not scan).

Usage

code_setwd(code_text)

Arguments

code_text

the code text for a single file (character vector), ideally comment-free (as produced by code_remove_comments())

Value

a data frame with columns setwd_call (the setwd(...) text as written) and line (its line number). Empty frame when none are found.

Examples

code_text <- c(
  "setwd('D:/Dropbox/project')",
  "x <- read.csv('data.csv')"
)
code_setwd(code_text)
#> # A tibble: 1 × 2
#>   setwd_call                   line
#>   <chr>                       <int>
#> 1 setwd('D:/Dropbox/project')     1