我很好奇以下代码是否可以转换为tidyverse代码。我尝试过dplyr :: mutate并且无法让它正常工作。
df$Gender[df$Gender == "M"] <- "Man"
df$Gender[df$Gender == "Male"] <- "Man"
df$Gender[df$Gender == "F"] <- "Woman"
df$Gender[df$Gender == "Female"] <- "Woman"
df$Gender[df$Gender == "M & F"] <- "Man and Woman"
df$Gender[df$Gender == "Male & Female"] <- "Man and Woman"
答案 0 :(得分:5)
这是一种方式,dplyr::case_when()
:
df$Gender <- dplyr::case_when(
df$Gender %in% c("M", "Male") ~ "Man",
df$Gender %in% c("F", "Female") ~ "Woman",
df$Gender %in% c("M & F", "Male & Female") ~ "Man and Woman",
TRUE ~ NA_character_)
或者,如果您想使用典型的dplyr::
/ magrittr::
管道链方法:
df <- df %>% mutate(Gender = case_when(
Gender %in% c("M", "Male") ~ "Man",
Gender %in% c("F", "Female") ~ "Woman",
Gender %in% c("M & F", "Male & Female") ~ "Man and Woman",
TRUE ~ NA_character_))
最后,提示:当你需要分组很多独特的值时,使用case_when()
(或嵌套的ifelse()
s,或子集化的赋值等)会变得相当繁琐。避免大部分痛苦的一种方法是使用命名向量用字典样式的“查找表”替换每个值(术语非正式 - 有些背景,请参阅wiki on "associative array")。根据我的经验,这通常是最干净的:
# the unique values
gender_values <- c("M","Man","Male","F","Woman","Female","MF","male-female")
# associate unique values with our new labels: "m", "f", and "b"
gender_lkup <- setNames(c("m","m","m","f","f","f","b","b"), gender_values)
# suppose this is a column of a df
raw_column <- sample(gender_values, 10, replace=TRUE)
# create a clean one with `gender_lkup`
clean_column <- gender_lkup[raw_column]
# inspect the two vectors side-by-side
data.frame(original=raw_column, cleaned=clean_column)