问题
Once again, I apologize for asking this type of question, but the R world is so large that sometime I feel lost, even if I have read some of the best book related with R. I have the following DB
ID=rep((1:3),3)
x<-as.Date("2013-1-1")
y<-as.Date("2013-1-2")
z<-as.Date("2013-1-3")
DATE<-c(x,x,x,y,x,y,z,z,z)
TRAP<-c(1,1,1,3,2,3,2,1,3)
IN<-data.frame(ID,DATE,TRAP)
and I would like to produce a binary variable (RESULT) according to the following conditions: if the DATE and the TRAP is the same for the different ID, then RESULT>y otherwise RESULT>n, like this
RESULT<-c("y","y","y","y","n","y","n","n","n")
OUT<-cbind(IN,RESULT)
I think that the ifelse
function should be used, but I don't know how to explicit the condition of equality controlling for each ID...
As always, every suggestion is greatly appreciated!
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/16143908/how-to-generate-binary-variable-according-to-the-conditions-of-other-variables