CodexBloom - Programming Q&A Platform

Trouble with using pivot_longer from tidyr to reshape a data frame with nested lists in R 4.3

👀 Views: 6532 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
r tidyr data-wrangling R

I'm getting frustrated with I recently switched to This might be a silly question, but I'm trying to reshape a data frame with nested lists using the `pivot_longer` function from the `tidyr` package, but I'm running into issues with the data structure... My data frame looks something like this: ```r library(tidyr) library(dplyr) # Sample data frame with nested lists my_data <- data.frame( id = 1:3, values = I(list(c(10, 20), c(30), c(40, 50, 60))) ) print(my_data) ``` When I attempt to apply `pivot_longer`, I want to convert the nested lists in the `values` column into separate rows. However, I keep getting the following behavior: ``` behavior in `pivot_longer()`: ! need to convert `values` to a valid data frame. ``` I have tried using `unnest` as a preliminary step, but it seems to be ineffective in this case. Here's what I tried: ```r my_data_long <- my_data %>% unnest(values) %>% pivot_longer(cols = values, names_to = "value_type", values_to = "value") ``` This results in the same behavior message. I've read through the documentation and attempted variations of the `pivot_longer` function, such as specifying `names_prefix` and `values_drop_na`, but nothing seems to resolve the scenario. What am I missing here? How can I effectively reshape this data frame with `pivot_longer` while handling nested lists? Any help or insight into this would be greatly appreciated! For context: I'm using R on macOS. Thanks in advance! This issue appeared after updating to R latest. I appreciate any insights!