R中的嵌套for循环错误(软件包extRemes)

我正在尝试在r中创建二维矢量,然后使用命令bloxplot()对其进行绘制。

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”返回参数值(位置,比例和形状),它们均来自“ extRemes”包。

我正在尝试将向量附加到向量(2D向量)上,但是错误消息显示为Error: object 'e' not foundError in boxplot(e[i]) : object 'e' not found

我还尝试将“ e

numbers <- c(10,10000)
e <- c()
for (i in 1:length(numbers)) {
e[i] <- c()
for(j in 1:100) {
a <- revd(numbers[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

有没有其他方法可以做到这一点而没有错误?

eblisjiang 回答:R中的嵌套for循环错误(软件包extRemes)

如果我做对了,这就是做到这一点的一种方法。至少对我而言,使用矩阵或向量的索引似乎比使用append()更像R。如果您想多次使用同一功能,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))

enter image description here

本文链接:https://www.f2er.com/3156191.html

大家都在问