我正在使用胶水包在报告中生成动态文本。当我使用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
答案 0 :(得分:3)
原因可能是glue
中case_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"