0

I want to apply the same function to a list of dataframes and create a new list with new dataframes. Actually, I am very close to the solution to the problem but I stopped and I could not find the solution online.

O_peaks = lapply(O, function(x){
               get_peaks(O[[x]][[1]], O[[x]][[2]], 
                         ignore_threshold = 0, span = 71, strict = TRUE, x_unit = "", x_digits = 3)
}) 

I think I misused the [[x]]. I tested a similar code:

O_peaks = lapply(O, function(x){
  get_peaks(O[[1]][[1]], O[[1]][[2]], 
            ignore_threshold = 0, span = 71, strict = TRUE, x_unit = "", x_digits = 3)
    })

In this case, I obtain a new list with the same number of dataframes of O, but since I wrote O[[1]][[1]], O[[1]][[2]] the new dataframes contain just the information from the first dataframe in O.

Are there any suggestions about how to apply the same function to all my dataframes?

Thank you in advance.

Agnese
  • 1
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Feb 20 '20 at 21:17
  • 1
    Hard knowing without an example, but I'd try changing `get_peaks(O[[x]][[1]], O[[x]][[2]],` to `get_peaks(x[[1]], x[[2]],` – Brian Davis Feb 20 '20 at 21:20
  • Could you please share a reprex of how your data frames look like, & what you want to do with them (i.e. what is the function supposed to do)? It's gonna help others figure out what's going on. Additionally, this is more of a general advice, but consider giving your data frames & variables informative names (e.g. "data_list" instead of "O"), it's going to make the coding much easier. – Adam B. Feb 20 '20 at 21:20
  • Thank you, @BrianDavis! It works! – Agnese Feb 21 '20 at 05:24
  • I'm glad it worked @Agnese. When providing a list to `lapply`, it's helpful to imagine each list item iteratively looping as your function's argument. Your original code probably would have worked if you used `1:length(O)` instead of `O` as the `lapply` input. – Brian Davis Feb 21 '20 at 20:04

1 Answers1

0

The X you are using for indexing is each of the dataframes in your list, so that is probably not what you want. And when you write O[[1]][[1]] you are asking for the first column in the first dataframe in your list. If you have a function, say foo, that receives a data frame as parameter and returns the data frame you need, could do something like

lapply(O, foo)
nsm
  • 319
  • 1
  • 9