group lists and use function on the groups

Viewed 27

I have some big lists, which include multiple inner lists with two data frames. One list looks like this:

Sample_list <- list(list("data","meta"),
                    list("data","meta"),
                    list("data","meta"),
                    list("data","meta"))
names(Sample_list)<-c("r1_S1","r1_S2","r2_S1","r2_S2")

This is just the structure of the list, the original list includes data frames which are called "meta" and "data" and is much longer (goes until r5_S2).

Also I have a function, which interpolates between S1 and S2 by using the "data" and the "meta" dataframes. The function works like this:

Interpolate_stations(Station1_meta,Station1_data,Station2_meta,Station2_data) 

Now I want to use lapply() with the named function on these groups but only for interpolating between r1_S1 and r1_S2, r2_S1 and r2_S2, r3_S1 and r3_S2 and so on.

It would be very nice, to have a function which does this automatically, since I have many of these big lists and going through them would take a lot of time. Is there a way to do this automatically? Thanks in advance

1 Answers

You can use lapply with Reduce to apply the function to both element of each list:

lapply(Sample_list, \(x) Reduce(Interpolate_stations, x))

For instance, with paste:

lapply(Sample_list, \(x) Reduce(paste, x))

$r1_S1
[1] "data meta"

$r1_S2
[1] "data meta"

$r2_S1
[1] "data meta"

$r2_S2
[1] "data meta"

Or with mapply:

lapply(Sample_list, \(x) mapply(Interpolate_stations, x[[1]], x[[2]]))
Related