Created
September 27, 2024 00:04
-
-
Save alexholcombe/2ec141beec36ac7640fa296dd236203c to your computer and use it in GitHub Desktop.
In R how to call a function with each element of a list, passing the element from the list as the first parameter for the function, and concatenate the results into a tibble?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Created mostly by Github Copilot | |
| # Define a function that takes at least one parameter and returns a tibble | |
| example_function <- function(element, additional_param) { | |
| tibble( | |
| element = c(element,2*element), | |
| additional_info = additional_param | |
| ) | |
| } | |
| # Create a list of elements | |
| example_list <- list(3, 5, 7) | |
| # Call the function with each element of the list as the first parameter and concatenate the results into a tibble | |
| result <- map_dfr(example_list, ~ example_function(.x, additional_param = "Extra")) | |
| # Print the result | |
| print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment