更新时间:2023-02-07 14:10:47
这是使用plyr
做到这一点的一种方法:
Here is a way to do it with plyr
:
R> ddply(IN, .(DATE,TRAP), transform, RESULT=ifelse(length(ID)>1,"y","n"))
ID DATE TRAP RESULT
1 1 2013-01-01 1 y
2 2 2013-01-01 1 y
3 3 2013-01-01 1 y
4 2 2013-01-01 2 n
5 1 2013-01-02 3 y
6 3 2013-01-02 3 y
7 2 2013-01-03 1 n
8 1 2013-01-03 2 n
9 3 2013-01-03 3 n
请注意,行已重新排序.
Note that the rows have been reordered.
使用data.table
的另一种解决方案:
Another solution with data.table
:
R> DT <- data.table(IN)
R> DT[,RESULT:=ifelse(.N>1,"y","n"), by=list(DATE,TRAP)]
R> DT
ID DATE TRAP RESULT
1: 1 2013-01-01 1 y
2: 2 2013-01-01 1 y
3: 3 2013-01-01 1 y
4: 1 2013-01-02 3 y
5: 2 2013-01-01 2 n
6: 3 2013-01-02 3 y
7: 1 2013-01-03 2 n
8: 2 2013-01-03 1 n
9: 3 2013-01-03 3 n
这里没有重新排序.
或使用基础ave
:
IN <- within(IN, { RESULT <- ave(TRAP, list(DATE, TRAP),
FUN= function(x) ifelse(length(x) > 1, "y", "n"))})
# ID DATE TRAP RESULT
# 1 1 2013-01-01 1 y
# 2 2 2013-01-01 1 y
# 3 3 2013-01-01 1 y
# 4 1 2013-01-02 3 y
# 5 2 2013-01-01 2 n
# 6 3 2013-01-02 3 y
# 7 1 2013-01-03 2 n
# 8 2 2013-01-03 1 n
# 9 3 2013-01-03 3 n