Giter Site home page Giter Site logo

here_here's Introduction

Ode to the here package

TL;DR

  1. Install here.

    install.packages("here")
  2. Use it.

    library(here)
    here("data", "file_i_want.csv")

This works, regardless of where the associated source file lives inside your project. These paths will also “just work” during interactive development, without incessant fiddling with the working directory of your IDE’s R process.

here::here() works like file.path(), but where the path root is implicitly set to "the path to the top-level of my current project". See The Fine Print for the underlying heuristics. If they don't suit, use the more powerful package rprojroot directly. Both here and rprojroot are written by Kirill Müller and are available on CRAN.

Admitting you have a problem

If the first line of your #rstats script is setwd("C:\Users\jenny\path\that\only\I\have"), I will come into your lab and SET YOUR COMPUTER ON FIRE.

Mash-up of rage tweets by @jennybc and @tpoi.

Do you:

  • Have setwd() in your scripts? PLEASE STOP DOING THAT.
    • This makes your script very fragile, hard-wired to exactly one time and place. As soon as you rename or move directories, it breaks. Or maybe you get a new computer? Or maybe someone else needs to run your code? We show a very accessible way to go cold turkey and eliminate the setwd() gotcha from your code.
  • Fanny around with working directory a lot? During development and/or at run time? YOU CAN STOP DOING THAT TOO.
    • Classic problem presentation: Awkwardness around building paths and/or setting working directory in projects with subdirectories. Especially if you use R Markdown and knitr, which trips up a lot of people with its default behavior of “working directory = directory where this file lives”. We show a very accessible way to specify paths in your project’s .R and .Rmd files, regardless of where they live.

Read my blog post “Project-oriented workflow” for more about why setwd() is so problematic and often associated with other awkward workflow problems. Never fear: there are solutions!

Actual demonstration of here::here()

I will let this code run.

What does here think the top-level of current project is? The package displays this on load or, at any time, you can just call here().

library(here)
#> here() starts at /Users/jenny/rrr/here_here
here()
#> [1] "/Users/jenny/rrr/here_here"

Build a path to something in a subdirectory and use it.

here("one", "two", "awesome.txt")
#> [1] "/Users/jenny/rrr/here_here/one/two/awesome.txt"
cat(readLines(here("one", "two", "awesome.txt")))
#> OMG this is so awesome!

Don’t try this at home, folks! But let me set working directory to a subdirectory and prove to you that the same code as above, for getting the path to awesome.txt, still works.

setwd(here("one"))
getwd()
#> [1] "/Users/jenny/rrr/here_here/one"
cat(readLines(here("one", "two", "awesome.txt")))
#> OMG this is so awesome!

The fine print

here::here() figures out the top-level of your current project using some sane heuristics. It looks at working directory, checks a criterion and, if not satisfied, moves up to parent directory and checks again. Lather, rinse, repeat.

Here are the criteria. The order doesn't really matter because all of them are checked for each directory before moving up to the parent directory:

  • Is a file named .here present?
  • Is this an RStudio Project? Literally, can I find a file named something like foo.Rproj?
  • Is this an R package? Does it have a DESCRIPTION file?
  • Is this a remake project? Does it have a file named remake.yml?
  • Is this a projectile project? Does it have a file named .projectile?
  • Is this a checkout from a version control system? Does it have a directory named .git or .svn? Currently, only Git and Subversion are supported.

If no criteria match, the current working directory will be used as fallback. Use set_here() to create an empty .here file that will stop the search if none of the other criteria apply. dr_here() will attempt to explain why here decided the root location the way it did. See the function reference for more detail.

here_here's People

Contributors

bambooforest avatar chendaniely avatar jennybc avatar krlmlr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

here_here's Issues

here() ignores .here file

I really love this package, thank you. I'm hoping someone can help with a problem I'm regularly having with here() where it ignores the .here file and instead chooses the R project file directory.

> dr_here()
here() starts at /Users/X/Github/mygit, because it contains a file matching `[.]Rproj$` with contents matching `^Version: ` in the first line
> set_here(getwd())
File .here already exists in /Users/X/Google Drive/SI/DataScience/mygit
> here()
[1] "/Users/X/Github/mygit"

If I unload and reload the package, here() points to the desired directory:

> detach("package:here", unload=TRUE)
> library("here")
here() starts at /Users/X/Google Drive/myfiles
Attaching package: ‘here’
The following object is masked from ‘package:lubridate’:
    here
> dr_here()
here() starts at /Users/X/Google Drive/myfiles, because it contains a file `.here`

here package does not work in Rmarkdown if {r, include=FALSE}

I have realized that by knitting exactly the same code in R markdown with {r ,include= FALSE} instead of {r ,eval= FALSE} for the code that includes the "here" function, the knitting does not work. In my specific case, the error that shows up says "error in here("Datasets","FA_GL.csv"): unused argument "FA_GL.csv" Calls: .... withVisible -> eval -> eval -> read.csv -> read.table Execution halted.

both {r ,include= FALSE} and {r ,eval= FALSE} work fine when the code is runned in R, the problem only arises when the document is knitted. Is that supposed to happen?

Question regarding best practice

Hello, thank you very much for letting us use the here package.
I heard many good things about it so I tried to use it myself.
I think I like the here idea, but (shame) I am not sure I understand it correctly, or how it fits my current use case.
Say I have a tree like

my_root_dir/         
|-- .here            
|-- data             
|   |-- today        
|   |-- tomo         
|   `-- yesterday    
|-- log              
`-- my_script.rscript
`-- my_logic.r

I want to execute the my_script.rscript (a she-bang script that leverage docopt or optparse) from anywhere and execute some logic in my_logic.r that would leverage the here package to do stuff in all sub-directories.
When I do /a/b/c/d/my_root_dir/my_script.rscript --someoption the here() logic is likely to place my in the /a (it does when I try)

Right now I do (please do not kill me)

if(!interactive()) setwd(dirname(getopt:::get_Rscript_filename()))
library(here)

which seems very paradoxical...

Am I missing something ?
Is it considered edge case because of interactive() ?

Kind regards

error on shared network

We work on shared network drive over VPN. Have been using here package without any issues when we open a .Rproject file located on the shared drive. Sometimes ( may be because of slow internet speed), rstudio throws cannot connect to internet error when connected via VPN. In this scenario we use the desktop shortcut of Rstudio and set the working dir to the shared drive and work with the respective R files. However, here function still recognizes the "C:/Users/name/Documents" as the working directory and does not read the files on the shared working dir. If we remove the here command from read.csv, the files read normally as expected. Any suggestion on how to make here command work in the above scenario ?
I did the following after setting working dir

here::set_here()
File .here already exists in P:\shared drive\ folder\projects\r_projects\covid_Dashboard\app

here::here()
[1] "C:/Users/username/Documents"

Missing advantage of here

First, thank you for advertising "here". It makes it even easier to use relative paths. Second, one advantage of the package that you do not mention is that it becomes possible to do away with "paste0" commands for file names based on variables. Hence, it becomes possible to code something like this without having to mess around with "paste".

for (obs in 1:length(directory_list$name)) {

  # Get file name and Google Drive ID
  file_name <- directory_list$name[obs]
  file_id <- directory_list$id[obs]
  print(file_name)

  # Download file
  drive_download(
    as_id(file_id),
    path = here("data", file_name),
    overwrite = TRUE
  )
}

If you think it worthwhile, I can write up a smaller version of this and add it. If you think it would distract from the central message, that is fine too.

Is it possible to use here() scheduling scripts with cron?

If you could possibly clarify this, it would help greatly. My current attempt to use here() is rather naive, I understand. I put the question out on Stackexchange and the essence is - can one find a way to use set_here() and subsequently here() to provide a base-path to all subdirectories to the script. I cannot use projects due to reasons I have explained in the post. I did not want to duplicate the stackexchange post here hence posted the link.

feature request: smart path completion

Thank you for the fantastic package. I tend to use it a lot with notebooks inside R projects. The only hurdle is that since my notebooks sit in, say, here('notebook'), path completion inside here::here() picks up from within here('notebook'), as opposed to here(). For instance, in the following instance, while inside here('vignettes'), path suggestion starts from within here('vigenttes')

image

I always add and then remove a ../ to the path to work around it. I was wondering if it can be automatically handled at least inside RStudio IDE. I understand that it might be beyond the package scope.

Can't load package

I have installed here package and have used it a few times but I am now getting this error on trying to load the package.

library('here')
Error: package or namespace load failed for ‘here’:
.onLoad failed in loadNamespace() for 'here', details:
call: normalizePath(path.expand(path), winslash, mustWork)
error: path[1]="C:/RStudio": The system cannot find the file specified

possible to only check for .here files and ignore other criteria?

Hi Jenny,

First of all thanks for your amazing package - I use it daily and it simplifies work a lot. I have one question though. Is it possible to tell here to ignore Rprofile files and only look for files named .here? I would love to place the .here file to a higher level in the hierarchy of folders. However, since I'm having an R Project on a lower level, the .here file is currently ignored.

Maybe this could be passed as an additional parameter?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.