错误:在case_when中使用glue()时必须是字符,而不是粘合/字符

时间:2017-09-18 15:23:19

标签: r dplyr

我正在使用胶水包在报告中生成动态文本。当我使用dplyr::case_when在条件之间切换时,我从胶水中得到错误。

library(dplyr); library(glue)
one_car <- mtcars[10, ]

# Throws error:
answer <- case_when(
  one_car$mpg < 25 ~ glue(row.names(one_car), " has bad mileage"),
  one_car$mpg >= 25 ~ glue(row.names(one_car), " has good mileage")  
)
  

错误:必须是字符,而不是粘合/字符

case_when无胶水工作:

answer <- case_when(
  one_car$mpg < 25 ~ 0,
  one_car$mpg >= 25 ~ 1  
)

胶水在单独运行时起作用:

glue(row.names(one_car), " has bad mileage")
#> Merc 280 has bad mileage

1 个答案:

答案 0 :(得分:3)

原因可能是gluecase_when类的不兼容性。

str(glue(row.names(one_car), " has bad mileage"))
#Classes 'glue', 'character'  chr "Merc 280 has bad mileage"

快速解决方法是将其强制转换为character

case_when(
   one_car$mpg < 25 ~ as.character(glue(row.names(one_car), " has bad mileage")),
   one_car$mpg >= 25 ~ as.character(glue(row.names(one_car), " has good mileage"))  
  )
#[1] "Merc 280 has bad mileage"