problems when using source, <<-, local/global variables and environments in R

旧街凉风 提交于 2019-12-11 15:52:14

问题


See below for my reprex of my issues with source, <-, <<-, environments, etc. There's 3 files, testrun.R, which calls inputs.R and CODE.R.

    # testrun.R (file 1)

    today <<- "abcdef"

    source("inputs.R")

    for (DC in c("a", "b")) {
      usedlater_3 <- paste("X", DC, used_later2)
      print(usedlater_3)
      source("CODE.R", local = TRUE)
    }

    final_output <- paste(OD_output, used_later2, usedlater_3)
    print(final_output)



    # #---- file 2
    # # inputs.R
    # used_later1 <- paste(today, "_later")
    # used_later2 <- "l2"
    # 
    # #---- file 3
    # # CODE.R
    # OD_output <- paste(DC, today, used_later1, usedlater_2, usedlater_3)

I'm afraid I didn't learn R or CS in a proper way so I'm trying to catch up now. Any bigger picture lessons would be helpful. Previously, I've been relying on a global environment where I keep everything (and save/keep between sessions), but now I'm trying to make everything reproducible, so I'm using RStudio to run local jobs that start from scratch.

I've been trying different combinations of <-, <<-, and source(local = TRUE) (instead of local = FALSE). I do use functions for pieces of code where I know the inputs I need and outputs I want, but as you can see, CODE.R uses variables from both testrun.R, the loop inside testrun.R, and input.R. Converting some of the code into functions might help ? but I'd like to know of alternatives as well given this case.

Finally you can see my own troubleshooting log to see my thought process:

  • first run: variable today wasn't found, so I made today <<- "abcdef" double arrow assignment
  • second run: DC not found, so I will switch to local = TRUE
  • third run: but now usedlater_2 not found, so i will change usedlater_2 to <<-. (what about usedlater_1? why didn't this show up as error? we'll see...)
  • result of third run: usedlater_2 still not found when CODE.R needs it. out of ideas. note: used_later2 was found to create used_later3 in the for loop in testrun.R.

来源:https://stackoverflow.com/questions/57454576/problems-when-using-source-local-global-variables-and-environments-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!