gpt4 book ai didi

从 R 函数返回图

转载 作者:行者123 更新时间:2023-12-03 14:54:15 27 4
gpt4 key购买 nike

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

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)

}

有任何想法吗?

最佳答案

这有效。根据建议,您可以使用列表保存多个对象:

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然后调用它来绘制图形:
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 函数返回图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19622028/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com