从 R 函数返回图 [英] Return plot from R function

查看:64
本文介绍了从 R 函数返回图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我的 R 函数不会返回或打印绘图?代码如下.除了情节之外,所有代码似乎都可以正常工作.无论我做什么,当函数被调用时,我都无法让 R 创建绘图.在网上环顾四周,我找不到任何不起作用的原因.

Why won't my R function return or print a plot? The code is below. All of the code seems to work fine, except for the plot. No matter what I do, I can't get R to create the plot when the function is called. Looking around online, I can't find any reason why this wouldn't work.

powerc.fun <- function(n,sigma,r){

a <- 0.05
d <- seq(-20,20,2)

power <- rep(NA,length(d))
p.lab <- rep(NA,length(d))

for (j in 1:length(d)){

  mu1 <- 110
  mu2 <- mu1-d[j]  

  reject <- rep(NA,r)

  for (i in 1:r){

    sample1 <- rnorm(n,mu1,sigma)
    sample2 <- rnorm(n,mu2,sigma)

    sample.t <- t.test(sample1,sample2)
    p.val <- sample.t[3]

    reject[i] <- p.val<a 

    power[j] <- sum(reject)/length(reject)
    p.lab[j] <- paste('d=',d[j],sep='')

  }}

d.power <- cbind(d,power)

return(d.power)

p.plot <- plot(d.power[,1], d.power[,2], type="l", xlab=bquote(H[a]), ylab="Power", main="Power Calculations for Two Sample T Test")

print(p.plot)
return(p.plot)

}

有什么想法吗?

推荐答案

这有效.按照建议,您可以使用列表保存多个对象:

This works. As suggested, you can save more than one object by using a list:

powerc.fun <- function(n,sigma,r){

a <- 0.05
d <- seq(-20,20,2)

power <- rep(NA,length(d))
p.lab <- rep(NA,length(d))

for (j in 1:length(d)){

  mu1 <- 110
  mu2 <- mu1-d[j]  

  reject <- rep(NA,r)

  for (i in 1:r){

    sample1 <- rnorm(n,mu1,sigma)
    sample2 <- rnorm(n,mu2,sigma)

    sample.t <- t.test(sample1,sample2)
    p.val <- sample.t[3]

    reject[i] <- p.val<a 

    power[j] <- sum(reject)/length(reject)
    p.lab[j] <- paste('d=',d[j],sep='')

  }}

d.power <- cbind(d,power)
p.plot <- plot(d.power[,1], d.power[,2], type="l", xlab=bquote(H[a]), ylab="Power", main="Power Calculations for Two Sample T Test")

return(list(p.plot, d.power))

}

# prints the plot and saves d.power values
output <- powerc.fun(100,0.1,10)

# d.power values
output[[2]]

但可能你更喜欢只保存 d.power 然后调用它来绘制图形:

But probably you prefer just to save d.power and then call it for plotting the graph:

powerc.fun <- function(n,sigma,r){

a <- 0.05
d <- seq(-20,20,2)

power <- rep(NA,length(d))
p.lab <- rep(NA,length(d))

for (j in 1:length(d)){

  mu1 <- 110
  mu2 <- mu1-d[j]  

  reject <- rep(NA,r)

  for (i in 1:r){

    sample1 <- rnorm(n,mu1,sigma)
    sample2 <- rnorm(n,mu2,sigma)

    sample.t <- t.test(sample1,sample2)
    p.val <- sample.t[3]

    reject[i] <- p.val<a 

    power[j] <- sum(reject)/length(reject)
    p.lab[j] <- paste('d=',d[j],sep='')

  }}

d.power <- cbind(d,power)

return(d.power)

}

# saves d.power
output <- powerc.fun(100,0.1,10)

# plot
p.plot <- plot(output[,1], output[,2], type="l", xlab=bquote(H[a]), ylab="Power", main="Power Calculations for Two Sample T Test")

这篇关于从 R 函数返回图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆