我有以下数据:
我想从“ TITLE
”中创建一个变量“ NAME
”,其值分别为MASTER
,MISS
,MR
,{{1 }}和MRS
。使用dplyr软件包,OTHER
有时类似于MISS
,MLLE
有时显示为MRS
或Ms
。
我尝试过:
MME
但是我不确定这是最好的方法。而且我不知道如何创建值“ Title_Master <- titanic2 %>%
filter(str_detect(Name, "Master") & Sex == "male") %>%
mutate(Title = "Master")
Title_Miss <- titanic2 %>%
filter((str_detect(Name, "Miss") | str_detect(Name, "Mmlle")) & Sex ==
"female") %>%
mutate(Title = "Miss")
Title_Mr <- titanic2 %>%
filter(str_detect(Name, "Mr") & Sex == "male") %>%
mutate(Title = "Mr")
Title_Mrs <- titanic2 %>%
filter((str_detect(Name, "Mrs") | str_detect(Name, "Ms") |
str_detect(Name, "Mme")) & Sex == "female") %>%
mutate(Title = "Mrs")
T_Title <- rbind(Title_Master, Title_Miss, Title_Mr, Title_Mrs)
”。
答案 0 :(得分:1)
#Always includes libraries and data set used is important for reproduciblity
library(tidyverse)
library(stringr)
#install.packages("titanic")
library(titanic)
titanic2 <- titanic::titanic_test
titanic2 %>% mutate(Title = case_when(str_detect(Name, "Master") & Sex == "male" ~ "Master",
str_detect(Name, "Miss|Mmlle") & Sex == "female" ~ "Miss",
str_detect(Name, "Mr") & Sex == "male" ~ "Mr",
str_detect(Name, "Mrs|Ms|Mme") & Sex == "female" ~ "Mrs",
TRUE ~ "OTHER")) %>% group_by(Sex, Title) %>% summarise(N=n())
# A tibble: 6 x 3
# Groups: Sex [?]
Sex Title N
<chr> <chr> <int>
1 female Miss 78
2 female Mrs 73
3 female OTHER 1
4 male Master 21
5 male Mr 240
6 male OTHER 5