Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

r - Error in eval(expr, envir, enclos) - contradiction?

Edited to give a fuller example of code and specific issue

I'm writing a function to produce time series plots of stock prices. However, I'm getting the following error

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

Here's an example of the function:

plot.prices <- function(df1234) {
  require(ggplot2)
  g <- ggplot(df1234, aes(x= as.Date(Date, format= "%Y-%m-%d"), y= df1234[, 3], 
              colour= brewer.pal(12,"Set3")[1])) + geom_point(size=1)
  g + geom_point(aes(x= date, y = df1234[, 4], 
                 colour= brewer.pal(12,"Set3")[2]), size=1)

  # ... code not shown...
  g
}

And example data:

spy <- read.csv(file= 'http://ichart.finance.yahoo.com/table.csv?s=SPY&d=11&e=1&f=2012&g=d&a=0&b=29&c=1993&ignore=.csv', header= T)

plot.prices(spy) # produces error
g <- ggplot(spy, aes(x= as.Date(Date, format= "%Y-%m-%d"), y= spy[, 3], 
              colour= brewer.pal(12,"Set3")[1])) + geom_point(size=1)
  g + geom_point(aes(x= as.Date(Date), y = spy[, 4], 
                 colour= brewer.pal(12,"Set3")[2]), size=1)
## does not produce error

As you can see, the code is identical. I get an error if the call to ggplot() is INSIDE the function but not if the call to ggplot() is OUTSIDE the function.

Anyone have any idea why the seeming contradiction?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error occur because you use df[, 7] in gglpot2, use column name Adj.Close will fix the problem.

 g <- ggplot(df, aes(x= as.Date(Date, format= "%Y-%m-%d"),
                  y= Adj.Close)) + geom_point(size=1)

In fact the error , it is a scoping error. aes can't find the df environnement. It tries to look for it the global scope .

if you you want to use use indexing calls , you can use aes_string for example , and manipulate strings not expressions

plot.prices <- function(df) {
  require(ggplot2)

  df$Date <- as.Date(df$Date, format= "%Y-%m-%d")

  g <- ggplot(df, aes_string(x= 'Date',
                      y= colnames(df)[7])) + geom_point(size=1)

  # ... code not shown...
  g
}

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...