Say I have the following data input into R
x <- c(1,1,0,0,0,0)
y <- c(1,0,1,0,0,0)
z <- c(0,0,0,0,1,1)
p <- c(0,0,0,1,1,0)
data <- data.frame(x,y,z,p)
Now I want to introduce a new variable in data called 'cat'
within cat I want to assign 'a' values to any observation where 1 appears in either x or y o appears in both. I want to assign the value 'b' to observations where 1 appears in either/both of z and p.
x
,y
that are1
doesn't have an intersect withz
orp
having1
valuesAs a first step, I did
rowSums
on columnsx
andy
Double negation on the above result and adding
0
givesSame thing when applied to columns
z
andp
but I add1
givesIf you add the above two results, will get
This can be used as a numeric index so that if I use
c("b", "a")[!!rowSums..]
, the2
values will be replaced byb
and1
witha
.