Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中传递上一个函数的对象_R_Function_Ggplot2_Environment - Fatal编程技术网

如何在R中传递上一个函数的对象

如何在R中传递上一个函数的对象,r,function,ggplot2,environment,R,Function,Ggplot2,Environment,我正在为自己创建一些函数,在控制台仍在运行时,我不知道如何继续使用从一个函数返回到另一个函数的对象(例如值)。例如: first <- function(x){ return(x) } second <- function(y){ z <- x + y return(z) } 我希望值为10。在这种特殊情况下,函数second()显然找不到对象x,因为后者是在first()环境中分配的 这种编程方式类似于ggplot(),例如: ggplot(aes(x = x, y =

我正在为自己创建一些函数,在控制台仍在运行时,我不知道如何继续使用从一个函数返回到另一个函数的对象(例如值)。例如:

first <- function(x){
return(x)
}

second <- function(y){
z <- x + y
return(z)
}
我希望值为10。在这种特殊情况下,函数second()显然找不到对象x,因为后者是在first()环境中分配的

这种编程方式类似于ggplot(),例如:

ggplot(aes(x = x, y = y), data = data) +
  geom_point()
我知道这种类型的编程意味着使用环境,但我不能让它工作。有什么建议吗

谢谢

编辑

看着github中的ggplot包,我想:

hh_first <- function(data) {

  h <- structure(list(data = data), class = c("hh"))

  h
}

"+.hh" <- function(e1, e2) {

  add_hh(e1, e2)

}

add_hh <- function(h, object) {

  h$data <- paste(h$data, object, sep = "")
  h$data

}

hh_second <- function(data) {

  data

}
返回字符串“嗨,你好吗?”。在本例中,加号运算符用于类“hh”的对象。 欢迎您提供有关代码或此类编码可能产生的错误的任何建议。

尝试:

first <- function(x){
  return(x)
}

second <- function(x ,y){
  z <- x + y
  return(z)
}

second(first(5), 5)

再看一遍后,我可能错过了你要找的东西,如果错过了,请告诉我,我将删除或更新答案;实际上,它使用自己的特殊函数来添加
ggplot2:::add_ggplot
。ggplot2包重载
+
-运算符,复制该过程的说明包括创建一个新类,该类将被分派到适当的代码。您应该搜索泛型函数。我认为这个要求太宽泛了。如果你决定走这条路,你应该阅读Venables和Ripley的“编程”或Hadley的“高级R”,谢谢大家的回答。伊恩·韦斯利的解决方案很好,但不能完全说服我。我将搜索ggplot包中的泛型函数以获得一个想法,如图42所示;第一(5)%>%第二(5)
hh_first('Hi') +
  hh_second(', how are you?')
first <- function(x){
  return(x)
}

second <- function(x ,y){
  z <- x + y
  return(z)
}

second(first(5), 5)
myX <- first(5)

second(myX, 5)
library(magrittr) # Which uses pipes, %>%, to pass the results of a function to the first variable of the second function
first(5) %>% second(5)