在其他变量的某些条件下,我试图在dataset中创建一个新变量。基本上,我想简化有关父母教育的资料,即父母分开的资料,并建立一个新的资料,考虑到家长的最高教育程度。例如,如果父亲教育级别为1,母亲教育水平为0,则新变量中此行的值将为1。
我试图在另一个变量中使用mutate()和case_when()函数,但我不明白为什么现在不行。当我尝试创建一个只有NA's的列时,当我从它打印一个表时,结果是:
<范围0表>
我为条件使用的两个变量的类是“标号”和“因子”。
首先,我尝试了以下命令(我正在简化代码):
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'))那我做错什么了?非常感谢。
发布于 2020-02-06 00:41:06
你可以玩弄这些价值观。希望这能有所帮助。
#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 NAhttps://stackoverflow.com/questions/60084851
复制相似问题