r - “`[[<-`(`*tmp*`, i, value = ) 中的错误:在级别 1 没有这样的索引”将 for 循环结果分配给列表
问题描述
我有一个数值向量列表。对于每个向量,我想使用 for 循环确定内核密度峰值的 x 值。打印结果时运行 for 循环可以正常工作。尝试将结果存储在列表中时,出现以下错误:
“
[[<-
(*tmp*
, i, value = d$x[c(F, diff(diff(d$y) >= 0) < 0)]) 中的错误:第 2 级没有这样的索引
我原始代码中的错误消息
返回:“...在级别 1 没有这样的索引”。
谁能帮我解决这个错误?提取核密度峰值的 x 值的代码来自计算直方图或密度函数中的峰值,第三个答案。
set.seed(1234)
x <- list(col1 = c(rnorm(100, mean = 3), rnorm(100, mean = 4)),
col2 = c(rnorm(100, mean = 3), rnorm(100, mean = 4)))
# Works fine
output <- vector("list", length(x))
for (i in (x)){
d <- density(i)
d$x[c(F, diff(diff(d$y) >= 0) < 0)] %>% print()
}
# Does not work
output <- vector("list", length(x))
for (i in (x)){
d <- density(i)
d$x[c(F, diff(diff(d$y) >= 0) < 0)] -> output[[i]]
}
解决方案
作为x
一个列表,您需要遍历它的索引来存储输出。
output <- vector("list", length(x))
for (i in seq_along(x)){
#Can also use
#for (i in 1:length(x)){
d <- density(x[[i]])
d$x[c(F, diff(diff(d$y) >= 0) < 0)] -> output[[i]]
}
或者,使用lapply
会自动给你一个列表
lapply(x, function(i) {
d <- density(i)
d$x[c(F, diff(diff(d$y) >= 0) < 0)]
})
推荐阅读
- r - 删除 r 中具有冗余信息的行(不仅仅是重复)
- docker - elasticsearch metricbeats docker安装错误
- node.js - Node.js 事件循环。为什么检查队列的回调在轮询队列的回调之前执行,而 Node.js DOC 则相反?
- swing - 停止 WindowBuilder for Eclipse 将组件放在括号内
- xgboost - 将 xgboost 的 GridSearchCV 与 DMatrix 一起使用
- excel - 调用公共过程时出现运行时错误 438
- java - 为什么这段代码等待 1000 毫秒而不是 500 毫秒?
- python - 调用特定函数
- graphql - Apollo readQuery,从缓存中获取数据
- twilio - 将出站呼叫重定向到外部 sip (Watson)