简体   繁体   中英

R not remembering objects written within functions

I'm struggling to clearly explain this problem.

Essentially, something has seemed to have happened within the R environment and none of the code I write inside my functions are working and not data is being saved. If I type a command line directly into the console it works (ie Monkey <- 0), but if I type it within a function, it doesn't store it when I run the function.

It could be I'm missing a glaring error in the code, but I noticed the problem when I accidentally clicked on the debugger and tried to excite out of the browser[1] prompt which appeared.

Any ideas? This is driving me nuts.

  corr <- function(directory, threshold=0) {
  directory <- paste(getwd(),"/",directory,"/",sep="")
  file.list <- list.files(directory)
  number <- 1:length(file.list)
  monkey <- c()
  
  for (i in number) {
    x <- paste(directory,file.list[i],sep="")
    y <- read.csv(x)
    t <- sum(complete.cases(y))
    if (t >= threshold) {
      correl <- cor(y$sulfate, y$nitrate, use='pairwise.complete.obs')
      monkey <- append(monkey,correl)}
  }
  #correl <- cor(newdata$sulfate, newdata$nitrate, use='pairwise.complete.obs')
  #summary(correl)
}
corr('specdata', 150)
monkey```

It's a namespace issue. Functions create their own 'environment', that isn't necessarily in the global environment.

Using <- will assign in the local environment. To save an object to the global environment, use <<-

Here's some information on R environments.

I suggest you give a look at some tutorial on using functions in R. Briefly (and sorry for my horrible explanation) objects that you define within functions will ONLY be defined within functions, unless you explicitly export them using (one of the possible approaches) the return() function.
browser() is indeed used for debugging, keeps you inside the function, and allows you accessing objects created inside the function.

In addition, to increase the probability to have useful answers, I suggest that you try to post a self-contained, working piece of code allowing quickly reproducing the issue. Here you are reading some files we have no access to.

在我看来,您必须在运行脚本时自己存储输出:

corr_out <- corr('specdata', 150)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM