将以字符向量为列的数据帧转换为长格式

问题描述 投票:0回答:1

我希望有人可以在DataCamp“使用R中的Shiny构建Web应用程序”课程中进行练习时遇到的问题,特别是通过转换他们在练习中使用的数据集来解决我的问题。

我已经使用readRDS函数导入了他们的数据集(RDS),看起来像这样:

 $ id         : int  10259 25693 20130 22213 13162 6602 42779 3735 16903 12734 ...
 $ cuisine    : chr  "greek" "southern_us" "filipino" "indian" ...
 $ ingredients:List of 39774
  ..$ : chr  "romaine lettuce" "black olives" "grape tomatoes" "garlic" ...
  ..$ : chr  "plain flour" "ground pepper" "salt" "tomatoes" ...
  ..$ : chr  "eggs" "pepper" "salt" "mayonaise" ...
  ..$ : chr  "water" "vegetable oil" "wheat" "salt"
  ..$ : chr  "black pepper" "shallots" "cornflour" "cayenne pepper" ...
  ..$ : chr  "plain flour" "sugar" "butter" "eggs" ...
  ..$ : chr  "olive oil" "salt" "medium shrimp" "pepper" ...
  ..$ : chr  "sugar" "pistachio nuts" "white almond bark" "flour" ...
  ..$ : chr  "olive oil" "purple onion" "fresh pineapple" "pork" ...
  ..$ : chr  "chopped tomatoes" "fresh basil" "garlic" "extra-virgin olive oil" ...

在他们的教程中,他们有一个经过转换的数据集,因此共有三列,id,菜式和配料,但是配料只有一种配料(意味着同一id有多行)。

通常,当我必须执行类似的操作时,我使用dplyr函数'gather',但这在这种情况下不起作用,因为它用于收集多列,而不是分散包含不同长度的字符向量的列。我还尝试使用了split()函数,但这要求您指定要将向量分隔为哪些列,因为它们的长度都不同,所以我不能这样做。

[如果有人可以给我一个想法,我将如何转换上述数据框以使其为长格式,我将不胜感激。

非常感谢!

r transformation rds
1个回答
0
投票
听起来像您正在寻找pivot_widerhttps://tidyr.tidyverse.org/reference/pivot_wider.html。这实际上与gather相反。

还应该提到,gather不再被更新,而已被替换为pivot_longer https://tidyr.tidyverse.org/reference/pivot_longer.html

© www.soinside.com 2019 - 2024. All rights reserved.