繁体   English   中英

r(包 extRemes)中的嵌套 for 循环错误

[英]Nested for-loop error in r (package extRemes)

我正在尝试使用命令bloxplot()在 r 然后 plot 中创建一个二维向量。

numbers <- c(10,100,1000,10000)

for (i in 1:length(numbers)) {
e[i] <- c()

for(j in 1:100) {
a <- revd(numbers[i], loc = 0, scale = 1, shape = 0, type ="GEV")
b <- fevd(x=a, type="Gumbel")
c <- as.numeric(unname(b$results$par[2]))
d <- append(d,c)
}
e[i] <- append(e[i],d)
}
boxplot(e[i])

“revd”生成随机变量,“number[i]”有不同的场景,“fevd”返回参数值(位置、比例和形状),它们都来自package“extRemes”。

我正在尝试 append 向量到向量(2D 向量),但出现错误消息Error: object 'e' not foundError in boxplot(e[i]): object 'e' not found

我也试过把“e <- c()”放在开头:

numbers <- c(10,100,1000,10000)
e <- c()
for (i in 1:length(numbers)) {
e[i] <- c()
for(j in 1:100) {
a <- revd(numbers[i], loc = 0, scale = 1, shape = 0, type ="GEV")
b <- fevd(x=a, type="Gumbel")
c <- as.numeric(unname(b$results$par[2]))
d <- append(d,c)
}
e[i] <- append(e[i],d)
}
boxplot(e[i])

然后错误消息增加到:

Error in e[i] <- c() : replacement has length zero
In addition: Warning message:
In e[i] <- append(e[i], d) :
  number of items to replace is not a multiple of replacement length

Error in plot.window(xlim = xlim, ylim = ylim, log = log, yaxs = pars$yaxs) : 
  need finite 'ylim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf

有没有不同的方法可以做到这一点而不会出错?

如果我做对了,这是一种方法。 至少对我来说,使用矩阵或向量的索引而不是使用append()似乎更多 R。 如果您想多次使用相同的 function,则replicate()也很方便。

library("tidyr")
library("extRemes")
library("ggplot2")
library("reshape2")

numbers <- c(10, 100, 1000, 10000)
num_reps <- 100

out_mat <- matrix(NA, nrow=num_reps, ncol=length(numbers))

scale_out <- function(data){
  mod <- revd(data, loc=0, scale=1, shape=0, type="GEV") %>% fevd(type="Gumbel")
  return(mod$results$par[[2]])
}


for (i in 1:length(numbers)){
  out_mat[, i] <- replicate(num_reps, scale_out(numbers[i]))
}

ggplot(melt(out_mat), aes(x=Var2, y=value)) + 
  geom_boxplot(aes(group=Var2))

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM