简体   繁体   中英

Combining two columns conditionally in R

I am trying to create a new column based on the values of two other columns. The values in the initial columns are 1 and 2. For the new column, I want the value to be 1 if the value in either of the first two columns is 1 and to be 0 otherwise. (If the person is either Vegetarian or Vegan , the VegYesNo column should be 1. Otherwise, it should be 0).

Vegetarian Vegan VegYesNo
1          2     1
2          2     0
2          1     1

I've searched the other questions on here and didn't find one that gave me an answer, but please let me know if you know of a question that has a solution that would work.

You can do that with:

mydata$VegYesNo <- as.integer(rowSums(mydata == 1) > 0)

Or with:

mydata$VegYesNo <- 1 * (rowSums(mydata == 1) > 0)

The result:

> mydata
  Vegetarian Vegan VegYesNo
1          1     2        1
2          2     2        0
3          2     1        1

Data:

mydata <- read.table(text="Vegetarian Vegan VegYesNo
1          2     1
2          2     0
2          1     1", header=TRUE)[,-3]

I suppose you have a data.frame

data = data.frame(vegetarian = c(1,2,2),Vegan = c(2,2,1))
data$VegYesNo = as.numeric(data$vegetarian==1 | data$Vegan==1)

Using dplyr package:

mydf <- text <- "Vegetarian Vegan
1          2
2          2
2          1"
mydf <- read.table(text = text, header = TRUE)

library(dplyr)
mydf %>% 
    mutate(VegYesNo=case_when(
        Vegetarian==1 | Vegan==1 ~ 1,
        TRUE ~ 0
    ))

The result is:

  Vegetarian Vegan VegYesNo
1          1     2        1
2          2     2        0
3          2     1        1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM