将以字符向量为列的数据帧转换为longform

时间:2020-02-04 11:27:44

标签: r transformation rds

我希望有人可以通过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()函数,但这要求您指定要将向量分隔为哪些列,因为它们的长度都不同,所以我不能这样做。

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

非常感谢!

1 个答案:

答案 0 :(得分:0)

听起来像您在寻找spreadhttps://tidyr.tidyverse.org/reference/spread.html。实际上,这与gather相反。

还应该提到gatherspread不再被更新,而已被替换为它们更明确的对应物pivot_longerpivot_wider:{{3} }和https://tidyr.tidyverse.org/reference/pivot_longer.html。但是,Datacamp可能尚未更新其课程以反映这一点。

相关问题