Reputation: 2077
I am attempting to create a new variable agreement
based on the four possible outcomes of two logical variables x
and y
. The code that I use is below, but I know that there has to be a better way to go about doing this. Any ideas?
mydata$agreement <- NA
mydata$agreement[!mydata$x & !mydata$y] <- 0
mydata$agreement[!mydata$x & mydata$y] <- 1
mydata$agreement[mydata$x & !mydata$y] <- 2
mydata$agreement[mydata$x & mydata$y] <- 3
mydata$agreement <- factor(mydata$agreement,
levels=c(0, 1, 2, 3),
labels=c("label 1", "label 2", "label 3", "label 4"),
ordered=FALSE)
Upvotes: 1
Views: 67
Reputation: 13314
This solution makes use of the predefined 'map' data frame:
z <- data.frame(x=c(F,F,T,T), y=c(F,T,F,T),agreement=paste('label',1:4))
# x y agreement
# 1 FALSE FALSE label 1
# 2 FALSE TRUE label 2
# 3 TRUE FALSE label 3
# 4 TRUE TRUE label 4
and merge
:
merge(d,z,by=c('x','y'))
# x y a agreement
# 1 FALSE FALSE e label 1
# 2 FALSE TRUE c label 2
# 3 FALSE TRUE d label 2
# 4 FALSE TRUE b label 2
# 5 FALSE TRUE g label 2
# 6 FALSE TRUE h label 2
# 7 TRUE FALSE a label 3
# 8 TRUE FALSE j label 3
# 9 TRUE TRUE i label 4
# 10 TRUE TRUE f label 4
where d
is a sample data frame:
d <- data.frame(x=sample(c(T,F),10,replace=T),y=sample(c(T,F),10,replace=T),a=letters[1:10])
# x y a
# 1 TRUE FALSE a
# 2 FALSE TRUE b
# 3 FALSE TRUE c
# ...
Upvotes: 0
Reputation: 40628
Here's a simple solution that conveys the intent:
# dummy data:
x <- sample(c(TRUE, FALSE), 100, replace=T)
y <- sample(c(TRUE, FALSE), 100, replace=T)
z <- factor(ifelse(x & y, 3, ifelse(x, 2, ifelse(y, 1, 0))),
levels=c(0, 1, 2, 3),
labels=c("label 1", "label 2", "label 3", "label 4"),
ordered=FALSE)
> table(z)
z
label 1 label 2 label 3 label 4
29 29 17 25
> table(x, y)
y
x FALSE TRUE
FALSE 29 29
TRUE 17 25
Upvotes: 2
Reputation: 41
Here is a marginally simpler solution:
mydata$agreement <- mydata$x + mydata$y*10
mydata$agreement <- factor(mydata$agreement,
levels=c(0, 1, 10, 11),
labels=c("label 1", "label 2", "label 3", "label 4"),
ordered=FALSE)
Upvotes: 2