r - 创建一个新变量
问题描述
我有以下数据:
我想TITLE
从“ ”创建一个变量“ NAME
”,其值为<code>MASTER, MISS
, MR
, MRS
AND OTHER
。MISS
, 有时是 like MLLE
,MRS
有时表现为Ms
or MME
, 使用 dplyr 包。
我试过这个:
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)
但我不确定这是最好的方法。而且我不知道如何创造价值“ OTHER
”。
解决方案
#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
推荐阅读
- python - python数组没有被填充
- python - 如何在 Python 中的朴素贝叶斯分类模型中进行 for 循环?
- java - Java 在子字符串重复一定次数后替换子字符串
- python - 删除数据框中所有数据点中的多余字符
- javascript - 作为 [object Object] 进入服务器的对象数组
- ios - SQLite:从 API 存储数据时应该使用整数主键还是整数?
- javascript - 新手 REST 服务器设置
- continuous-integration - 使用特定于应用程序的数据将数据库部署到不同的环境中
- python - 如何在类实例化中自动传递重复的 kwargs
- python-3.x - 使用 inset_axes 和 transData 时的宽度和高度错误