首页 > 解决方案 > 创建一个新变量

问题描述

我有以下数据:

图片

我想TITLE从“ ”创建一个变量“ NAME”,其值为<code>MASTER, MISS, MR, MRSAND OTHERMISS, 有时是 like MLLE,MRS有时表现为Msor 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”。

标签: rdplyrstringr

解决方案


#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

推荐阅读