Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unlist the result of pivot wider in R

Tags:

r

tidyverse

Does anyone know of a way to unlist the output from the pivot_wider function in R? The following code returns a list in each cell of column A and a list in each cell of column B. What I'd ideally like is the Item (e.g. Orange) repeated for each observation in the list cells A and B.

library(tidyverse)
set.seed(111)
# What I have
data_bad <- tibble(
  Item = rep(c("Orange", "Lemon", "Sugar", "Parsley"),each = 6),
  Source = rep(c("A","A","A","B","B","B"), times = 4),
  Value = runif(length(Item))
) %>%
  pivot_wider(names_from = Source, values_from = Value, values_fn = list(value = list))

# What I'd like
data_good <- tibble(
  Item = rep(c("Orange", "Lemon", "Sugar", "Parsley"),each = 6),
  A = runif(n = length(Item)),
  B = runif(n = length(Item))
)

Thank you for your help!

like image 393
David Avatar asked Jan 23 '26 15:01

David


1 Answers

We can use unnest from tidyr

library(dplyr)
library(tidyr)
data_bad %>% 
   unnest
like image 134
akrun Avatar answered Jan 26 '26 07:01

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!