1

我在“分解”字符变量和标记/重新编码不同级别时遇到了一些麻烦。有没有一种有效的方法(即更少的编码)与tidyverseBase R诸如recodefct_collapse等等......谢谢

#This is what I have (a character variable)
x <- c("No", "Yes", "No2", "No3", "Maybe", "undecided", 
       "probably", "dont know", NA)
x
#I want a factor with three ordered levels as follows:

#where No = c("No", "No2", "No3")
#Yes = c("Yes")
#other = c("Maybe", "undecided", "probably")
#NA = c("dont know", NA)
# and the levels would be 0 = "No",  1 = "Yes" and 2 = "Maybe"
#that is:
#xfact
# [1] No    Yes   other
# Levels: No Yes other
#
# as.integer(xfact)
# [1] 0, 1, 2```
4

1 回答 1

0

这样的事情应该这样做:

library(tidyverse)

x <- c("No", "Yes", "No2", "No3", "Maybe", "undecided", 
       "probably", "dont know", NA)

na_if(x, "dont know") %>% 
  fct_collapse(
    no = c("No", "No2", "No3"),
    yes = c("Yes"),
    other = c("Maybe", "undecided", "probably")
  ) %>% 
  fct_inorder()
#> [1] no    yes   no    no    other other other <NA>  <NA> 
#> Levels: no yes other

reprex 包(v0.3.0)于 2020 年 1 月 13 日创建

于 2020-01-13T13:16:01.107 回答