2012-06-15 69 views
2

我想寫一個函數來創建一組數字的圖並添加一個迴歸線。到目前爲止,我仍然可以創作情節,但是我會在情節上得到一個錯誤,或者某種空的迴應。R-多個返回函數來創建一個圖形

我沒有不返回空值的迴歸線功能如下:

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

這是做你想做的嗎?

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 
+0

+1 ggplot(在複雜的圖形,我不會建議'STR(P)'雖然;);格子圖形也可以這樣存儲。 – baptiste

+0

@baptiste這是一個很好的觀點! 'str(p)'將成爲哈德利唯一能夠理解的令人討厭的咒語。 'str(p)'更重要的是讓我們得到了一些東西,而在OP的函數的返回值上調用'str'。 – Justin

3

你真正需要的函數返回劇情對象?還是足以直接繪製它?

我沉迷於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 
相關問題