简体   繁体   English

基于其他列添加列

[英]Adding column based on other column

If I have a dataset called data.如果我有一个名为 data 的数据集。

I need to add a column based on this logic 0 if "gender" in data is 0 or 1 or 3;如果数据中的“性别”为 0 或 1 或 3,我需要基于此逻辑 0 添加一列; 1 if "gender" in data is 2 1 如果数据中的“性别”为 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:假设gender只取可能的值 0、1 和 2,我们可以尝试使用ifelse ,如下所示:

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

We can use case_when() from the dplyr library for finer grain control:我们可以使用dplyr库中的case_when()来进行更精细的粒度控制:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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