0
votes

I have a function in R which takes a Participant ID as input and outputs a dataframe with just one row and 10 columns. To call the function all I need to do is function(id) and I get:

column1 column2 etc
value value etc

I want to run the function on every ID from a list of IDs and output a tibble with one row per participant where the first column is the ID number followed by all the normal columns from the function output, like so:

ID column1 column2 etc
01 value value etc
02 value value etc
03 value value etc

My instinct (as an inexperienced R user) is to try and do this in a for loop but I assume there will be a better way to do it with purrr. Is map_df what I want here? And how do I add the extra column for Participant ID?

2

2 Answers

0
votes

Yes, using map_df would help by specifying the .id argument.

fn <- function(id) {
  #some function that returns a dataframe
}

#If your dataframe is called `df` with `ID` column in it
result <- purrr::map_df(df$ID, fn, .id = 'ID')
0
votes

Consider using rbindlist

library(data.table)
rbindlist(lapply(df$ID, fn), idcol = "ID")