问题描述:

I have written the following function. Unfortunately when I run it, it runs for about 2 seconds and then returns absolutely nothing but when i run it using debug it seems to run perfectly. The code also returns the heads of the files read in fine but it doesn't assign anything to an object so after I run the function I can type head of the file again and it returns an error. I am a little stumped so any pointers would be much appreciated!

Thanks

 Extremes <- function (siteno){

# reads in the weather data for the specipied site

Butterfly_data <- read.csv(paste("~/Project Data/Site Subsets/SITE", siteno, ".csv", sep = ""))

Precip <- read.csv(paste("//ueahome5/ressci5/zuw13bqu/data/NTProfile/Desktop/EOBS European data/SiteWeather/rr/Weather.Site.", siteno, ".csv", sep = ""))

Tmin <- read.csv(paste("//ueahome5/ressci5/zuw13bqu/data/NTProfile/Desktop/EOBS European data/SiteWeather/tn/Weather.Site.", siteno, ".csv", sep = ""))

Tmax <- read.csv(paste("//ueahome5/ressci5/zuw13bqu/data/NTProfile/Desktop/EOBS European data/SiteWeather/tx/Weather.Site.", siteno, ".csv", sep = ""))

for (i in 1:length(Precip[,1])){ # turns missing values into NA values for precip, max and min temp

if (Precip[i,1] < -900){

Precip[i,1] <- NA

}}

for (i in 1:length(Tmax[,1])){

if (Tmax[i,1] < -900){

Tmax[i,1] <- NA

}}

for (i in 1:length(Tmin[,1])){

if (Tmin[i,1] < -900){

Tmin[i,1] <- NA

}}

ExtPrecip <- mean(Precip[,1], na.rm = TRUE) + sd(Precip[,1], na.rm = TRUE) # finds the extreme of each weather variable

ExtTmax <- mean(Tmax[,1], na.rm = TRUE) + sd(Tmax[,1], na.rm = TRUE)

ExtTmin <- mean(Tmin[,1], na.rm = TRUE) + sd(Tmin[,1], na.rm = TRUE)

return(c(head(Precip),head(Tmin),head(Tmax)))

}

网友答案:

I think you are trying to assign the various objects to the top level environment. Functions have their own environments, so assignments there exist only during the evaluation of the functions (which is why you can see the objects when debugging). As soon as you your function returns, the objects in the body of the function cease to exist.

In order to work around that, you can use <<- (i.e. Butterfly_data <<- read.csv(...)), as well as anytime you modify those objects within the function.

Please keep in mind that <<- use is generally discouraged, and there is almost always a better way to do something than using <<-.

For example, in this case, you could have returned a list with all your objects, and written a separate function that runs through the lists and produces the heads:

Extremes <- function(siteno) {
  # bunch of stuff

  return(list(Precip=Precip, Tmax=Tmax, Tmin=Tmin))
}             
data.list <- Extremes("mysiteno")
lapply(data.list, head)  # view the heads
list2env(data.list)      # if you really want objects available at top level directly
相关阅读:
Top