简体   繁体   中英

Adding column based on other column

If I have a dataset called data.

I need to add a column based on this logic 0 if "gender" in data is 0 or 1 or 3; 1 if "gender" in data is 2

How can I create a code to add in?

Assuming gender would only take on the possible values 0, 1, and 2, we can try using ifelse as follows:

data$flag <- ifelse(data$gender <= 1, 0, 1)

We can use case_when() from the dplyr library for finer grain control:

data$flag <- case_when(
    gender %in% c(0, 1) ~ 0,
    gender == 2 ~ 1,
    # add other mappings here
    TRUE ~ NA
)

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