Skip to content
Prev 384620 / 398525 Next

Help with looping a function over a list of dataframes:

*I hope this is more succinct.*

*I have the following code: *
list_df$position_tab_5$ID <- unlist(lapply(list_df$position_tab_5$midpoint,
function(x) ifelse(any(abs(x - list_df$position_tab_4$midpoint) <= 1),1,0)))


It compares every observation from the midpoint column from dataframe 2 to
every observation from the midpoint column from dataframe 1. It does this
in order to find any values within +/- 1 of the value, and if it satisfies
this criteria then it assigns it a unique id of 1. If not then a value of
0.

In the example below, pos_tab_5 is being compared to pos_tab_4:

Pos tab 4:
Object minimum maximum midpoint
2600    4             22             13
2604    42           85             63.5
2606    142         172           157
2609    223         241           232
2611    393         421           407

Pos tab 5:
Object minimum maximum midpoint ID
2580    3             21             12           1
2581    43           85             64           1
2585    132         168           150         0
2586    223         241           232         1
2589    391         419           405         0

The reason it compares every observation from pos_tab_(n) to pos_tab_(n-1)
is because some of the dataframes are of different row length, and so by
comparing every observation from one DF to another, it can find any values
that are within +/- 1 of each other. (which is the main thing i'm looking
for)

I need help looping this function over a list of dataframes. The list of
dataframes called: list_df contains 121 different dataframes all
representing a different time point of the object.

This is what i have so far:
for(i in seq_along(list_df)){
   list_df$position_tab_[[i]]$ID <-
     unlist(lapply(list_df$position_tab_[[i]]$midpoint, function(x)
                 ifelse(any(abs(x - list_df$position_tab_[[i-1]]$midpoint)
<= 1),1,0)
            ))
}
On Sat, 4 Jul 2020 at 14:44, Eric Berger <ericjberger at gmail.com> wrote: