0

我有这个数据:

    # A tibble: 169 x 5
   `Topical Anesthesist`             `Skin Glue`                   `Sedation Servi~ `Child Life Ther~ Hypnosis     
   <chr>                             <chr>                         <chr>            <chr>             <chr>        
 1 No, because we do not see/treat ~ No, because we do not see/tr~ No               No                No           
 2 No, we do not have one available  Yes                           No               No                No           
 3 Yes: LET/LAT (lidocaine, epineph~ Yes                           Yes              No                No           
 4 Yes: LET/LAT (lidocaine, epineph~ Yes                           Yes              No                No           
 5 Yes: LET/LAT (lidocaine, epineph~ Yes                           No               No                No           
 6 Yes: LET/LAT (lidocaine, epineph~ Yes                           Yes              No                Yes: during ~
 7 Yes: LET/LAT (lidocaine, epineph~ Yes                           Yes              No                Yes: during ~
 8 Yes: LET/LAT (lidocaine, epineph~ Yes                           Yes              No                Yes: during ~
 9 Yes: LET/LAT (lidocaine, epineph~ Yes                           Yes              No                Yes: during ~
10 Yes: LET/LAT (lidocaine, epineph~ Yes                           Yes              No                No   

根据列的不同,我的值是“是”,后面是各种字符链(“是的,一整天”,“是的:全天”,等等......)。我所有的价值观都以是或否开始。我想用单词“Checked”替换以yes开头的每个值,并且用“Unchecked”替换以“No”开头的每个值(“Checked”和“Unchecked”是我在其余数据集和我的代码中使用的其他值使用它们)

我尝试:

data %>%
  mutate_all(.funs = fct_recode,
             "Checked" = starts_with("yes"),
             "Unchecked" = starts_with("no"))

我收到此错误:

starts_with()` 必须在选择函数中使用。

我不知道如何简单地解决我的问题...

谢谢你的帮助 !

4

1 回答 1

1

以下代码获取 starwars 数据集,查找以“bl”开头的每个条目并将其替换为“HA”:

library(dplyr)
data(starwars)
func = function(x){
  ifelse(grepl("^bl",x), "HA", x)
}

mutate_all(starwars, func)

按照这种模式,我建议您尝试以下方法:

func = function(x){
  ifelse(grepl("^Yes",x), "Checked", ifelse(grepl("^No",x), "Unchecked", x))
}
data %>% mutate_all(func)

或更优雅地使用case_when

func = function(x){
  case_when(grepl("^Yes", x) ~"Checked",
            grepl("^No", x) ~"Unchecked",
            TRUE ~as.character(x))
}

data %>% mutate_all(func)

于 2020-04-09T23:31:01.303 回答