簡體   English   中英

R-多次返回功能以創建繪圖

[英]R- multiple returns in function to create a plot

我想寫一個函數,創建一組數字的圖,並添加一個回歸線。 截至目前,我仍然可以創建情節,但我得到的情節錯誤,或某種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

對不起,如果這看起來非常挑剔,但在實際數據集中它可能會變得難看。

這樣做你想要的嗎?

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

你真的需要函數來返回繪圖對象嗎? 或者直接繪制它是否足夠?

對於那種東西,我沉迷於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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM