【发布时间】:2018-11-13 00:49:54
【问题描述】:
我想创建一个包含两列信息的新列,但其中一列位于不同的行上。下面是我想开始的示例数据框:
df <- data_frame(person = c(rep("Joe",4),rep("Bob",3)),
meal = c(seq(1:4),seq(1:3)),
food = c("Chicken", "Beef", "Soup and meal 2", "Lamb",
"Lamb","Salad and meal 1","Beef"),
dependencies = c(NA,NA,2,3,NA,1,NA),
solo_meal = c(1,1,0,1,1,0,1))
我想创建一个如下所示的新列:
data_frame(combined_meal = c("Chicken", "Beef", "Soup and Beef", "Lamb",
"Lamb","Salad and Lamb","Beef"))
如果使用依赖项,我想将“食物”与“膳食”结合起来。
我有一个包含多个依赖项的大型数据集,我需要将它们组合到一个字段中。我觉得应该有一个简单的方法来做到这一点,但我似乎想不出一个。
谢谢!
编辑: 我要感谢到目前为止发表评论的人。 tidyverse 选项最适合我的需求。我有一个想要添加的编辑 - 在搜索膳食时 - 我可能需要一起添加不止一顿饭。
df <- data_frame(person = c(rep("Joe",4),rep("Bob",3)),
meal = c(seq(1:4),seq(1:3)),
food = c("Chicken", "Beef", "Soup and meal 2", "Lamb and meal 3",
"Lamb","Salad and meal 1","Beef"),
dependencies = c(NA,NA,2,3,NA,1,NA),
solo_meal = c(1,1,0,1,1,0,1))
给出:
# A tibble: 7 x 5
person meal food dependencies solo_meal
<chr> <int> <chr> <dbl> <dbl>
1 Joe 1 Chicken NA 1
2 Joe 2 Beef NA 1
3 Joe 3 Soup and meal 2 2 0
4 Joe 4 Lamb and meal 3 3 1
5 Bob 1 Lamb NA 1
6 Bob 2 Salad and meal 1 1 0
7 Bob 3 Beef NA 1
我想要一列合餐:
# A tibble: 7 x 1
combined_meal
<chr>
1 Chicken
2 Beef
3 Soup and Beef
4 Lamb and Soup and Beef
5 Lamb
6 Salad and Lamb
7 Beef
如何递归添加餐点?最好使用 tidyverse。
再次感谢!
【问题讨论】:
-
重新编辑,为什么没有依赖乔的饭4?
-
我忘记在编辑中更新该列。现在应该修好了。