rvariable-assignmentmultiple-variable-return

assigning categoical values to multiple variables in r


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.


Solution

  • c("b", "a")[(!!rowSums(data[,1:2])) +0 + (!!rowSums(data[,3:4])+1)]
    #[1] "a" "a" "a" "b" "b" "b"