1

I have a list of numerical vectors. For each vector I want to determine the x-values for the kernal density peaks using a for loop. Running the for loop when printing the results works fine. When trying to store the results in a list I get the following error:

"Error in [[<-(*tmp*, i, value = d$x[c(F, diff(diff(d$y) >= 0) < 0)]) : no such index at level 2"

The Error message in my original code

returns: "... no such index at level 1".

Can anyone help me fixing this error? The code for extracting the x-values for the kernal density peaks came from Calculating peaks in histograms or density functions, third answer.

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]]
}
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81

3 Answers3

2

As x is a list you need to loop over it's index to store the output.

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]]
}

Alternatively, using lapply would automatically give you a list

lapply(x, function(i) {
   d <- density(i)
   d$x[c(F, diff(diff(d$y) >= 0) < 0)]
})
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Works perfectly Ronak! Can you explain why assiging using "for (i in x)" works for printing, but not for assigning to a list? – Adriaan Nering Bögel Jan 07 '20 at 10:14
  • 2
    @AdriaanNeringBögel When you are trying to assign value for first iteration `i` is 1st element of `x` i.e `x[[1]]`. So what you are trying to do is `output[[x[[1]]]]` which gives you the same error as you are getting now. – Ronak Shah Jan 07 '20 at 10:17
1

Is this what you are looking for ?

output <- vector("list", length(x))
j=0
for (i in (x)){
j=j+1
d <- density(i)
d$x[c(F, diff(diff(d$y) >= 0) < 0)] -> output[[j]]
}
JbL
  • 56
  • 5
1

In your original code, i is the elements in x, not the index of element. If you want to update output by index, you can try the code below

output <- list()
for (i in (x)){
d <- density(i)
d$x[c(F, diff(diff(d$y) >= 0) < 0)] -> output[length(output)+1]
}
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81