Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

r - Pivot wider produces nested object

This is regarding latest tidyr release. I am trying pivot_wider & pivot_longer function from library(tidyr) (Update 1.0.0)

I was trying to obtain normal iris dataset when I run below but instead I get nested sort of 3X5 dimension tibble, not sure whats happening (I read https://tidyr.tidyverse.org/articles/pivot.html) but still not sure how to avoid this

library(tidyr)
iris %>% pivot_longer(-Species,values_to = "count") %>% 
pivot_wider(names_from = name, values_from = count)

Expected Output: Normal Iris dataset (150 X 5 dimension)

Edit: I read below that if I wrap around unnest() I get expected output. I am not able to understand why to unnest it when we did not nest it anywhere. Any basic help would be appreciated. Want to understand the concept of what went wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I learnt from Akrun & other helpful friends & post (Not a bug or anything)

spread(., name, count) throws an error because we have multiple rows for each species x name. pivot_wider does a better job by providing a list-columns instead. If we add unique ID to each row then it works fine.

library(tidyverse)

iris %>%
  rowid_to_column() %>% 
  pivot_longer(-c(rowid, Species), values_to = "count") %>%
  pivot_wider(names_from = name, values_from = count) %>% 
  select(-rowid)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...