R code on Google docs

后端 未结 4 1009
既然无缘
既然无缘 2021-02-10 02:47

I\'m aware that you can publish spreadsheets on Google docs and then import them in R. However, let\'s say I have a function or some code I want to read in R (like in the sourc

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-10 03:35

    I would suggest Github or something similar for this type of situation.

    Just a few of the reasons for recommending Github:

    • Version control
    • Code highlighting
    • Collaboration
    • Ability to develop and host an R package on Github that others can install in R using the devtools package
    • Simple URL scheme that makes it easy to use source() to load functions

    Once you have posted your function to Github, you can easily load it as follows:

    require(RCurl)
    baseURL = c("https://raw.github.com/--username--/--repo-name--/master/")
    source(textConnection(getURL(paste0(baseURL, "path-to-scripts/script-name.R"))))
    

    Of course, you can easily wrap that into a function instead of having to type it out in each R session, or try some of the options in the devtools package.

    If you do this a lot, you might want to learn to make an R package and host it on Github. If you only need to do this once in a while, you might consider using "github:gist" instead. Each "gist" is assigned a numeric ID that can then easily be sourced using source_gist() from the devtools package as follows:

    source_gist("gist-id-number")
    

    Pretty hard to beat that, but you do have to make note of the ID numbers for your functions, or put all of your functions in one file and memorize one ID number...


    The reason I wouldn't recommend something like Google Docs to write your code is that it is generally a terrible idea to use "word processor" type software for such purposes as they might introduce hidden characters that would make your file difficult to source. Furthermore, the URL to the plain text version is a very obscure one that you won't be able to remember....

    Incidentally, it is possible to get the "txt" version of the file you've linked to in your post, but I'm not able to source() it--I have to open it in a text editor and copy and paste it into R. This is because of the file encoding which appears to be "UTF-8 (with BOM)". Anyone out there have tips on how to deal with that?

提交回复
热议问题