首页 > 解决方案 > “`[[<-`(`*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]]
}

标签: rlistfor-loop

解决方案


作为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)]
})

推荐阅读