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

前端 未结 2 664
北荒
北荒 2020-12-16 02:32

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 followi

相关标签:
2条回答
  • 2020-12-16 03:21

    I am not sure whether this is what you want, but it might help. I modified agstudy's code:

    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)
    
    library(ggplot2)
    library(RColorBrewer)
    
     plot.prices <- function(df) {
    
       df$Date <- as.Date(df$Date, format= "%Y-%m-%d")
    
       g <- ggplot(df, aes_string(x='Date', y= colnames(df)[3])) + 
                       geom_point(colour= brewer.pal(12,"Set3")[1], size=1)
    
       gg <- g + geom_point(aes_string(x='Date', y= colnames(df)[4]),
                       colour= brewer.pal(12,"Set3")[2], size=1)
       gg
     }
    
     plot.prices(spy)
    

    Here is code without using brewer.pal:

    library(ggplot2)
    
    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 <- function(df) {
    
       df$Date <- as.Date(df$Date, format= "%Y-%m-%d")
    
       g <- ggplot(df, aes_string(x='Date', y= colnames(df)[3])) + 
                       geom_point(colour= 'green', fill='green', size=1)
    
       gg <- g + geom_point(aes_string(x='Date', y= colnames(df)[4]),
                       colour= 'black', fill='black', size=1)
       gg
     }
    
     plot.prices(spy)
    
    0 讨论(0)
  • 2020-12-16 03:24

    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

    0 讨论(0)
提交回复
热议问题