0

I have a R code looking like below:

Region_TS <- function(index, scale = 1e+09, region){
  # Creates line graph of a variable of a Region over time
  # Input:
  #  index = index number of series
  #  scale = scaling number, 1, 1e+03, 1e+06, 1e+09 or 1e+12
  #  Region = string of region
  # Output: line graph "plot"
  if (scale == 1){
    labelstring <- ""
  }else if (scale == 1e+03){
    labelstring <- "in thousands"
  }else if (scale == 1e+06){
    labelstring <- "in millions"
  }else if (scale == 1e+09){
    labelstring <- "in billions"
  }else if (scale == 1e+12){
    labelstring <- "in trillions"
  }else{
    stop("Error! Enter correct scaling number!")
  }
  temp <- subset(Panel, Region == region)
  temp <- temp[,c(2,index)]
  temp[,2] <- temp[,2]/scale
  plot <- ggplot(data = temp, aes(x = temp[[1]], y = temp[[2]], group = 1))
  plot <- plot + geom_line()
  plot <- plot + ggtitle(paste(gsub("_", " ", names(temp)[2]), "of", region, sep = " "))
  plot <- plot + xlab("Year")
  plot <- plot + ylab(labelstring)
  plot
}

Region_TS(index = 5, scale = 1e+12, region = "Texas") 

When I run the last line, it gives me an error saying

Error in eval(expr, envir, enclos) : object 'temp' not found

However, the data.frame "temp" is defined correctly, as I get something like

    Year      GSP
474 2000 0.746433
475 2001 0.784956
476 2002 0.799937
477 2003 0.843715
478 2004 0.920387
479 2005 0.998092
480 2006 1.093794
481 2007 1.176966
482 2008 1.243331
483 2009 1.167233
484 2010 1.248511

when I insert "return(temp)" right before "plot <- ggplot ...".

I realize that this question is similar to some other questions, but they do not seem to give me a solution for the above problem.

Thank you for your help!

BrianDIngels
  • 127
  • 2
  • 8
  • The `aes()` function expects column names as symbols. You're passing `temp[[1]]` which is a vector of values. You should look into `aes_string()` if you want to set a column name via a character variable. – MrFlick Jan 19 '15 at 22:32
  • Thank you! Altering to "plot <- ggplot(data = temp, aes_string(x = names(temp)[1], y = names(temp)[2], group = 1))" solved the problem. – BrianDIngels Jan 19 '15 at 22:37

0 Answers0