在其他两个变量的条件下创建一个新变量

时间:2020-02-05 22:11:18

标签: mutate case-when

我正在尝试在其他变量的某些条件下在数据集中创建一个新变量。基本上,我想简化有关父母教育的信息(父母和父母分开),并创建一个新的考虑父母教育水平的信息。例如,如果父亲的教育水平为1,母亲的教育水平为0,则新变量中此行的值为1。

我正在尝试将mutate()case_when()函数一起使用,该函数在另一个变量中起作用,但是我不明白为什么现在不行。当我尝试时,它将创建一个仅包含NA的列,并且当我从中打印表格时,结果是:

<范围0表>

我用于条件的两个变量的类是'labelled'和'factor'。

首先,我尝试了以下命令(我正在简化代码):

dataset <- dataset %>% 
           mutate(NEW_EDUCATIONAL_VAR = case_when(MOTHER_EDUCATIONAL_VAR == '0' &  FATHER_EDUCATIONAL_VAR == '0' ~ '0',
                                                  MOTHER_EDUCATIONAL_VAR == '0' & FATHER_EDUCATIONAL_VAR == '1' ~ '1')

然后,我尝试考虑具有NA值的情况,因为某些行中存在NA:

dataset <- dataset %>% 
           mutate(NEW_EDUCATIONAL_VAR = case_when(is.na(MOTHER_EDUCATIONAL_VAR) & is.na(FATHER_EDUCATIONAL_VAR) ~ '99',
                                                  MOTHER_EDUCATIONAL_VAR == '0' & FATHER_EDUCATIONAL_VAR == '1' ~ '1')

当我使用这些功能为案件年龄创建一个新功能时,它起作用了。

dataset <- dataset %>% mutate(AGE_CAT = case_when(AGE >= 16 & AGE <= 18 ~ '0',
                                                   AGE >= 19 & AGE <= 24 ~ '1',
                                                   AGE >= 25 & AGE <= 29 ~ '2',
                                                   AGE >= 30 ~ '3'))

那么,我在做什么错?非常感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用这些值。希望这可以帮助。

#packages
library(tidyverse)

#sample data
Mother <- c(0,0,0,1,1,NA)
Father <- c(0,1,1,0,0,1)
df <- data.frame(Mother, Father)
str(df) #both Mother and Father columns are numeric

#mutate + case_when
df %>% 
  mutate(New = case_when(Mother == 0 & Father == 0 ~ 0, #condition 1
                         Mother == 0 & Father == 1 ~ 1, #condition 2
                         is.na(Mother) & Father == 1 ~ NA_real_, #condition 3
                         TRUE ~ 99)) #all other cases

输出:

  Mother Father New
1      0      0   0
2      0      1   1
3      0      1   1
4      1      0  99
5      1      0  99
6     NA      1  NA