r - r 中的嵌套 for 循环错误(包 extRemes)
问题描述
我正在尝试在 r 中制作一个二维向量,然后使用 command 绘制它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 found
并且Error 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。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))
推荐阅读
- sas - 仅保留与 sas 中的要求匹配的连续行,例如
- python - python2.7.12 不包含 numpy 也不包含 pip 所以我无法在 gromacs 中运行我的程序
- c++ - 如何打印调用函数的行号和文件名而不是 log.cpp?
- python - 下游类中不可访问的对象初始化属性
- python - 从脚本中更改目录后如何返回脚本目录?
- c# - 问题多实例代理wcf服务c#
- javascript - React Table:_pivotVal 将对象转换为字符串“[Object Object]”
- python - Python:Keras - 执行'next(trainBatch)',当我在火车文件夹中有36张图片时出现除以零错误
- ios - TableViewController 在搜索时填充,但不会加载初始视图
- c - 平方根作为运行时的输入