How to generate binary variable according to the conditions of other variables?

只愿长相守 提交于 2019-12-02 07:52:05
juba

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.


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

There is no reordering here.


Or using base 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

You could use duplicated for this:

IN$RESULT <- ifelse((duplicated(IN[,2:3])+duplicated(IN[,2:3],fromLast=TRUE))>0,
                       "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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!