Argument of lenght 0 error

Hi. I have two data frames (eeg and p1_1_a). They look like this:

> head(eeg)
  wave_1
1 18.959
2 19.432
3 20.384
4 20.489
5 21.012
6 21.571

> nrow(eeg)
[1] 849

> class(eeg$wave_1)
[1] "numeric"

> head(p1_1_a)
      Time  Latency Amplitude Peak_Lenght
1  57.1184  7.90738 -0.388889     8.44690
2 123.3470 15.49230 -0.917778     5.51634
3 191.0920 11.87220 -0.466667     6.55066
4 249.1710 15.49230 -0.871111     5.68873
5 325.5090 10.32080 -0.388889     5.34396
6 385.6040 12.56180 -0.684444     4.82680

> class(p1_1_a$Time)
[1] "numeric"

> nrow(p1_1_a)
[1] 10

I want to create a list consisting of the number from eeg$wave_1 that are the closest smaller numbers to each of the numbers in 1p_1_a$Time. So the list will be of 10 numbers and the first one will be 56.678 (eeg$wave_1[48]) as this is the closest smaller number to 1p_1_a$Time[1] (57.1184). I have written a loop:

list <- c()

for(i in 1:nrow(p1_1_a$Time)){
    if(eeg$wave_1 <= p1_1_a$Time[i]){
      list <- max(eeg$wave_1[eeg$wave_1 <= p1_1_a$Time[i]])
  }
}

But I get this error:

Error in 1:nrow(p1_1_a$Time) : argument of length 0

I have tried searching the web for an answer but I just cannot figure this out. Please help me.

here is a template for an approach you could use

set.seed(42)

(random_nums_main <- rnorm(10,mean=5,sd=2))
(random_nums_candidates <- rnorm(100,mean=5,sd=2))


do_match <- function(to_match_against,candidates){
  diffvals <- abs(to_match_against - candidates)
  min_diffvals_pos <- which.min(diffvals)
  candidates[min_diffvals_pos]
}

library(purrr)
list_of_closest_matches <- map_dbl(random_nums_main,
    ~do_match(.,random_nums_candidates)
    )

(results_in_df <- data.frame(main = random_nums_main,
                            matches = list_of_closest_matches))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.