R-多次返回功能以创建绘图

时间:2012-06-15 22:23:32

标签: r

我想编写一个函数来创建一组数字的图并添加回归线。截至目前,我仍然可以创建情节,但我得到的情节错误,或某种Null响应。

我没有返回no null的回归线的函数如下所示:

fun<-function(){
+   x<-c(1,2,3,4,5)
+   y<-c(1,2,3,4,5)
+   LR<-lm(x~y)
+   
+   return(plot(x,y))
+ }
> fun()

漂亮而漂亮,结果只是一个情节

如果我将回归线添加到图中,我仍然得到图,但我也得到一个空响应

> fun<-function(){
+   x<-c(1,2,3,4,5)
+   y<-c(1,2,3,4,5)
+   LR<-lm(x~y)
+   p<-plot(x,y)
+   a<-abline(LR)
+   return(p)
+ }
> fun()
NULL

或错误

> fun<-function(){
+   x<-c(1,2,3,4,5)
+   y<-c(1,2,3,4,5)
+   
+   LR<-lm(x~y)
+   
+   p<-plot(x,y)
+   a<-abline(LR)
+   
+   return(p,a)
+ }
> fun()
Error in return(p, a) : multi-argument returns are not permitted

或两个空值

> fun<-function(){
+   x<-c(1,2,3,4,5)
+   y<-c(1,2,3,4,5)
+   
+   LR<-lm(x~y)
+   
+   p<-plot(x,y)
+   a<-abline(LR)
+   
+   return(list(p,a))
+ }
> fun()
[[1]]
NULL

[[2]]
NULL

很抱歉,如果这看起来非常挑剔,但在实际数据集中它可能变得难看。

2 个答案:

答案 0 :(得分:4)

这样做你想要的吗?

fun <- function(x, y) {
  plot(x, y)
  abline(lm(x~y))
}

fun(1:10, 10:1)

如果您希望绘图对象返回进行进一步操作,可以使用ggplot

fun <- function(df) {
  ggplot(df, aes(X, y)) + geom_point()
}

df <- data.frame(x=1:10, y=10:1)
p <- fun(df)

# examine p
str(p)

# plot p
p

答案 1 :(得分:4)

你真的需要函数来返回绘图对象吗?或者直接绘制它是否足够?

我沉迷于ggplot2那种东西。此功能同时执行(打印绘图并将其作为对象返回)

fun <- function(dataset){
  require(ggplot2)
  p <- ggplot(dataset, aes(x = x, y = y)) + geom_smooth(method = "lm") + geom_point()
  print(p)
  return(p)
}

p1 <- fun(data.frame(x = c(1,2,3,4,5), y = rnorm(5)))
p1