CodexBloom - Programming Q&A Platform

R: implementing using purrr::map and data frames resulting in unexpected list structure

👀 Views: 39 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-02
r purrr dataframe R

I'm maintaining legacy code that I'm working through a tutorial and I'm testing a new approach and I'm trying to apply a function to each row of a data frame using `purrr::map`, but the output is not what I expected. I have the following data frame: ```r library(dplyr) my_data <- data.frame( id = 1:3, value = c(10, 20, 30), flag = c(TRUE, FALSE, TRUE) ) ``` I want to create a new list that contains results from a function that checks if the `value` is greater than 15. Here's the code I tried: ```r library(purrr) result <- my_data %>% pmap(~ if_else(..2 > 15, "Above", "Below")) ``` However, when I check the `result`, I see that it gives me a nested list instead of a flat character vector: ```r str(result) # Outputs: List of 3 ``` This is not what I intended. I was expecting a simple character vector such as `c("Below", "Above", "Above")`. I also tried using `map_chr` instead of `pmap`, but it doesn't seem to work with multiple columns. What am I doing wrong? Is there a better way to achieve this, or do I need to restructure my data or approach? Any guidance on the correct usage of these functions would be greatly appreciated! Thanks in advance! I'm using R 3.11 in this project. For reference, this is a production REST API. Am I missing something obvious? This is my first time working with R 3.11.