枢轴更宽会产生嵌套对象 [英] Pivot wider produces nested object

查看:41
本文介绍了枢轴更宽会产生嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与最新的 tidyr 版本有关。我正在尝试 pivot_wider & pivot_longer 来自 library(tidyr)(更新1.0.0)的功能

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

我在下面运行时尝试获取普通的虹膜数据集,但我却嵌套了3X5尺寸的小节,不确定发生了什么(我读了 https://tidyr.tidyverse.org/articles/pivot.html ),但仍不确定如何避免这种情况

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)

预期输出:正常虹膜数据集(150 X 5维度)

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

编辑:我在下面读到,如果我环绕unnest(),则会得到预期的输出。当我们没有将其嵌套在任何地方时,我无法理解为什么要取消嵌套。任何基本的帮助将不胜感激。想了解出什么问题的概念。

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.

推荐答案

据我从Akrun&其他乐于助人的朋友发布
(不是bug或其他内容)

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

spread(。,name,count)会引发错误,因为每个物种x名称都有多个行。 ivot_wider通过提供一个列表列来做得更好。如果我们向每行添加唯一的ID,则可以正常工作。

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)

这篇关于枢轴更宽会产生嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆