R函数:函数内部有绘图的奇怪行为

R函数:函数内部有绘图的奇怪行为,r,R,在函数中放置绘图时,我会出现奇怪的行为(使用“R Studio”0.99.484中带有R的ggplot) 我不明白为什么局部作用域变量不能用于生成绘图。也许你能启发我,告诉我正确的方法 下面是一个小代码片段,再现了我的问题: # This works: x1 <- seq(0,90,10) ggplot() + geom_line(aes(x=x1,y=x1)) # This yields error below: f1 <- function() { x2 <- seq

在函数中放置绘图时,我会出现奇怪的行为(使用“R Studio”0.99.484中带有R的ggplot)

我不明白为什么局部作用域变量不能用于生成绘图。也许你能启发我,告诉我正确的方法

下面是一个小代码片段,再现了我的问题:

# This works:
x1 <- seq(0,90,10)
ggplot() + geom_line(aes(x=x1,y=x1))

# This yields error below:
f1 <- function() {
  x2 <- seq(0,90,10)
  ret <- ggplot() + geom_line(aes(x=x2,y=x2))
  return(ret)
}
f1()

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

# This fixes the error: but why myX needs to be global?
f1 <- function() {
  myX <<- seq(0,90,10) 
  ret <- ggplot() + geom_line(aes(x=myX,y=myX))
  return(ret)
}
f1()

# This yields error below:
f2 <- function(d) {
  ret <- ggplot() + geom_line(aes(x=d,y=d))
  return(ret)
}
f2(x1)

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

# This fixes the error making all global: is this the right way to do it?
f2 <- function(d) {
  myX <<- d
  ret <- ggplot() + geom_line(aes(x=myX,y=myX))
  return(ret)
}
f2(x1)
#这项工作:

x1在第一个示例中,问题是您在函数内声明了一个变量,而该变量是该函数的局部变量。这就是为什么会出现错误:找不到对象“x2”


如果你想让这个变量在函数外部可访问,你可以使用操作符
,你应该真正使用数据帧。好的,谢谢你,我更新了我的问题并给你答案,因为现在它可以工作了。我不明白为什么ggplot不能访问本地定义的变量,但是,如果您可以详细说明…:)@不客气。我扩展了答案。我希望它能进一步澄清这个问题。
# Option 1: <<-
    f1 <- function() {
      x2 <<- seq(0,90,10)
      ret <- ggplot() + geom_line(aes(x=x2,y=x2))
      return(ret)
    }
    f1()

# Option2: assign  
    f1 <- function() {
      assign(x = "x2", value = seq(0,90,10), envir=.GlobalEnv)
      ret <- ggplot() + geom_line(aes(x=x2,y=x2))
      return(ret)
    }
    f1()
# Option 3: assignment outside the function
x2 <- seq(0,90,10)
f1 <- function() {
  ret <- ggplot() + geom_line(aes(x=x2,y=x2))
  return(ret)
}
f1()
f1 <- function() {
  x1 <- data.frame(x1 = seq(0,90,10))
  ret <- ggplot(x1, aes(x = x1, y= x1)) + geom_line()
  return(ret)
}
f1()