3

我想编写一个函数来创建一组数字的图并添加一条回归线。到现在为止,我仍然可以创建情节,但我要么得到情节错误,要么得到某种空响应。

我的函数没有返回不返回 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

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

4

2 回答 2

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
于 2012-06-15T22:29:16.313 回答
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
于 2012-06-15T22:30:57.850 回答