我的数据帧当前如下所示:
Tree Cookie Age
C1T1 A 10
C1T1 A 20
C1T1 A 30
C1T1 B 15
C1T1 B 20
C1T1 B 25
C1T2 A 12
C1T2 A 20
C1T2 B 5
C1T2 B 13
因此,对于每个";树";我有几个";Cookies";,对于每一块饼干,我都有不同的年龄(基本上代表了树生命的不同部分(。我想添加另一列,根据每棵树的最大年龄对其进行分类-最老cookie的最老年龄,在这种情况下,它将是两棵树中cookie A的最后年龄(因此,如果最大年龄<40,则将树分类为"年轻";如果最大年龄>40且<120,则将其分类为"中年";如果最老年龄>120,则分类为"老年"(。如有任何建议,我们将不胜感激!
好的,开始:我使用了dplyr
库来执行此操作,它为我提供了%>%
运算符和summarise()
函数。我还将您的数据帧命名为trees
。然后:
library(dplyr)
trees2 <- trees %>%
group_by(Tree = Tree) %>%
summarise(Age = max(Age))
trees2$Cat <- ifelse(trees2$Age < 40, "young", ifelse(trees2$Age > 120, "old", "mid-age"))
trees$Category = trees2$Cat[match(trees$Tree, trees2$Tree)]
以前,trees2
会是这样的:
> trees2
# A tibble: 2 x 2
Tree Age
<chr> <chr>
1 C1T1 30
2 C1T2 5
> trees2$Cat <- ifelse(trees2$Age < 40, "young", ifelse(trees2$Age > 120, "old", "mid-age"))
> trees2
# A tibble: 2 x 3
Tree Age Cat
<chr> <chr> <chr>
1 C1T1 30 young
2 C1T2 5 old
之后,使用科里在这篇文章中的建议,我把这个tibble放在原始表格中,最后一行是:
trees$Category = trees2$Cat[match(trees$Tree, trees2$Tree)]
这给了我:
> trees
Tree Cookie Age Category
1 C1T1 A 10 young
2 C1T1 A 20 young
3 C1T1 A 30 young
4 C1T1 B 15 young
5 C1T1 B 20 young
6 C1T1 B 25 young
7 C1T2 A 12 old
8 C1T2 A 20 old
9 C1T2 B 5 old
10 C1T2 B 13 old
一种使用cut
:的方法
trees_max <- trees %>%
group_by(Tree) %>%
summarise(max_age = max(Age))
breaks <- c(0, 40, 120, Inf)
labels <- c("young", "mid-age", "old")
trees_max$cat <- cut(trees_max$max_age, breaks, labels)
给你
> trees_max
# A tibble: 4 x 3
Tree max_age cat
<chr> <dbl> <fct>
1 C1T1 30 young
2 C1T2 20 young
3 C1T3 35 young
4 C1T4 77 mid-age