使用基于多个条件的值使用 dplyr 改变一个新列

时间:2021-01-21 22:26:37

标签: r dplyr mutate

我有一个包含多列的数据框,我想在其中创建一个包含基于列 status 的值的新列。

我是 R 新手,但我认为有可能做到这一点。

我的数据框 str() 是: str() 我的列 status 包含一个故障代码,其值为 240:12、05:03: 90:312 等。但有些代码不是故障代码,只是信息。所以我想创建一个新列,说明哪些代码是错误的,哪些不是。

我知道以“00”、“01”、“02”、“03”、“04”、“05”、“07”、“08”、“09”、“10”开头的代码, “11”、“12”、“14”、“15”、“16”、“17”、“20”、“21”、“60”、“240”、“600”不是错,其他是故障码。

Status 中的值为 character

我的解决方案是:

dataframe3 %>% 
mutate(Status_fault = case_when(startsWith(Status,C("00","01","02",
                "03","04","05","07","08","09","10","11",
                "12","14","15","16","17","20","21","60","240","600"))
       ~ "No fault",
        T ~ "fault"))

但这会导致

<块引用>

错误:mutate() 输入 Status_problem 有问题。 x 对象不可解释为因子 i 输入 Status_problemcase_when(...)

有人想解决这个问题吗? 我到处搜索堆栈溢出,但我找了这么久,我感觉我不能再直接思考了......

该问题与另一个使用 lapply 的问题相关联。 所以我做了一个新的解决方案:

dataframe3 %>% 
 mutate(Status_problem = case_when(lapply(c('00','01','02','03','04','05','07','08','09','10','11','12','14','15','16','17','20','21','60','240','600'),starts_with, X = Status)
       ~ "No fault",
        T ~ "fault"))

不幸的是,这导致:

<块引用>

错误:mutate() 输入 Status_problem 有问题。 xc("'c("00", "01", "02", "03", "04", "05", "07", "08", "09", "10", '不是一个函数、字符或符号", "' "11", "12", "14", "15", "16", "17", "20", "21", "60", "240", '不是函数、字符或符号", "' "600")' 不是函数、字符或符号") i 输入 Status_problemcase_when(...)

有人看到我做错了吗?

0 个答案:

没有答案