我正在处理一个鸟类数据集,其中每个人(ID)都具有其出生地(TERR),出生年份(YOB)和出生年份开始后的天数(DOB)。
通常,有多个个人具有相同的TERR,YEAR和DOB。在相同的TERR和YEAR中出生的人可能会更多,但是这些人的DOB不同(在此数据集中,第一组人的DOB比第二组人的“低” DOB)。
我想插入一个新列“ n”,其中每年第一组个人返回“ 1”,第二组个人返回“ 2”,第三组个人返回“ 3”。下一年,数字将恢复为“ 1”。
例如。
ID TERR YOB DOB N
1 A1 1982 148 1
2 A1 1982 148 1
3 A1 1982 148 1
4 A1 1982 185 2
5 A1 1982 185 2
6 A1 1985 137 1
7 A1 1985 137 1
8 BIAN 1989 132 1
9 BIAN 1989 132 1
10 BIAN 1989 132 1
11 BIAN 1992 155 1
12 BIAN 1992 155 1
13 BIAN 1992 155 1
14 BIAN 1992 254 2
15 BIAN 1992 254 2
16 BIAN 1992 254 2
17 BIAN 1994 164 1
18 BIAN 1994 164 1
19 GATE 1998 119 1
20 GATE 1998 119 1
21 GATE 1998 172 2
22 GATE 1998 172 2
23 GATE 1998 172 2
24 GATE 1999 153 1
25 GATE 1999 153 1
我对R很陌生,因此非常感谢您的帮助。我一直在尝试使用if_else函数,但步步为营。
最佳答案
按“ TERR”,“ YOB”分组后,使用“ DOB”的match
元素获得“ DOB”的unique
library(dplyr)
out <- df1 %>%
group_by(TERR, YOB) %>%
mutate(N1 = match(DOB, unique(DOB)))
identical(out$N, out$N1)
#[1] TRUE
out
# A tibble: 25 x 6
# Groups: TERR, YOB [7]
# ID TERR YOB DOB N N1
# <int> <chr> <int> <int> <int> <int>
# 1 1 A1 1982 148 1 1
# 2 2 A1 1982 148 1 1
# 3 3 A1 1982 148 1 1
# 4 4 A1 1982 185 2 2
# 5 5 A1 1982 185 2 2
# 6 6 A1 1985 137 1 1
# 7 7 A1 1985 137 1 1
# 8 8 BIAN 1989 132 1 1
# 9 9 BIAN 1989 132 1 1
#10 10 BIAN 1989 132 1 1
# ... with 15 more rows
或将'DOB'转换为
factor
并将其强制转换为numeric
df1 %>%
group_by(TERR, YOB) %>%
mutate(N1 = as.integer(factor(DOB, levels = unique(DOB))))
在
base R
和ave
中可以使用相同的方法with(df1, ave(DOB, TERR, YOB, FUN = function(x) match(x, unique(x))))
数据
df1 <- structure(list(ID = 1:25, TERR = c("A1", "A1", "A1", "A1", "A1",
"A1", "A1", "BIAN", "BIAN", "BIAN", "BIAN", "BIAN", "BIAN", "BIAN",
"BIAN", "BIAN", "BIAN", "BIAN", "GATE", "GATE", "GATE", "GATE",
"GATE", "GATE", "GATE"), YOB = c(1982L, 1982L, 1982L, 1982L,
1982L, 1985L, 1985L, 1989L, 1989L, 1989L, 1992L, 1992L, 1992L,
1992L, 1992L, 1992L, 1994L, 1994L, 1998L, 1998L, 1998L, 1998L,
1998L, 1999L, 1999L), DOB = c(148L, 148L, 148L, 185L, 185L, 137L,
137L, 132L, 132L, 132L, 155L, 155L, 155L, 254L, 254L, 254L, 164L,
164L, 119L, 119L, 172L, 172L, 172L, 153L, 153L), N = c(1L, 1L,
1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 1L, 1L)), .Names = c("ID", "TERR", "YOB",
"DOB", "N"), class = "data.frame", row.names = c(NA, -25L))
关于r - 根据分组变量返回数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50950423/