我有一个数据集,其中包含一些候选人的教育履历信息。例如,我有一个专栏,其中PhD学位的人必须包括他们的领域(如果适用的话),或者NA,如果没有。像这样
Participants PHD_Field
A Economics
B Sciences
C NA
D NA
E NA我需要创建一个列,并将它们的字段转换为1,并将N/As转换为0。你能帮我用密码在R里做这个吗?
发布于 2021-08-12 00:29:52
df$phd <- as.integer(!is.na(df$PHD_Field))过程分解:
is.na(df$PHD_Field) # is.na = is the value NA?1假假真真
!is.na(df$PHD_Field) # adding a ! (NOT) to reverse the logic; is the value NOT NA1真假假假
as.integer(!is.na(df$PHD_Field)) # as.integer = turn F into 0, and T into 11 1 1 0 0
df$phd <- as.integer(!is.na(df$PHD_Field)) # assign to the dataframe field phd
df
Participants PHD_Field phd
1 A Economics 1
2 B Sciences 1
3 C <NA> 0
4 D <NA> 0
5 E <NA> 0发布于 2021-08-11 23:54:59
library(tidyverse)
df1 <- data.frame(
stringsAsFactors = FALSE,
Participants = c("A", "B", "C", "D", "E"),
PHD_Field = c("Economics", "Sciences", NA, NA, NA)
)
df1 %>%
mutate(phd = as.integer(!is.na(PHD_Field)))
#> Participants PHD_Field phd
#> 1 A Economics 1
#> 2 B Sciences 1
#> 3 C <NA> 0
#> 4 D <NA> 0
#> 5 E <NA> 0发布于 2021-08-12 00:04:56
下面是使用ifelse的基本R解决方案
df$phd <- ifelse(is.na(df$PHD_Field), 0, 1)输出:
Participants PHD_Field phd
<chr> <chr> <dbl>
1 A Economics 1
2 B Sciences 1
3 C NA 0
4 D NA 0
5 E NA 0https://stackoverflow.com/questions/68750042
复制相似问题