Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中不重复地使用FORCAT重新编码多个值_R_Forcats - Fatal编程技术网

如何在R中不重复地使用FORCAT重新编码多个值

如何在R中不重复地使用FORCAT重新编码多个值,r,forcats,R,Forcats,我想使用forcats重新编码系数x,使用像yes=“bad”、yes=“2”、no=“3”、no=“good”这样的映射,但不重复代码。 类似于yes=levels(x)[1:2]和no=levels(x)[3:4] <!-- language-all: lang-r --> library(forcats) x <- factor(c("bad", "2", "2", "good&q

我想使用
forcats
重新编码系数
x
,使用像yes=“bad”、yes=“2”、no=“3”、no=“good”这样的映射,但不重复代码。 类似于
yes=levels(x)[1:2]
no=levels(x)[3:4]

<!-- language-all: lang-r -->


    library(forcats)

    x <- factor(c("bad", "2", "2", "good", "3", "3", "3", "good"),
                levels = c("bad",2,3,"good"))

    fct_recode(x, yes = "bad", yes = "2", no = "3", no = "good")
    #> [1] yes yes yes no  no  no  no  no 
    #> Levels: yes no

    # I don't want to repeat yes and no
    levels(x)[1:2] # should be yes
    #> [1] "bad" "2"
    levels(x)[3:4] # should be no
    #> [1] "3"    "good"

图书馆(供猫用)
x[1]是是否否否否
#>级别:是否
#我不想重复是和否
级别(x)[1:2]#应为是
#>[1]坏的“2”
级别(x)[3:4]#应为否
#>[1]“3”良好

由(v0.3.0)创建于2020-10-03。您可以使用

library(forcats)
#By explicitly mentioning the levels to collapse
fct_collapse(x, yes  = c('bad', '2'), no = c('3', 'good'))
#[1] yes yes yes no  no  no  no  no 
#Levels: yes no

#By using levels
fct_collapse(x, yes  = levels(x)[1:2], no = levels(x)[3:4])
#[1] yes yes yes no  no  no  no  no 
#Levels: yes no