使用 modify() 和 map_int() 函数时出现错误

I've got an error when I use the modify() and map_int() functions

id=1:5
age=c(30,30,37,35,33)
gender=c("f","m","f","f","m")
weight=c(155,177,NA,144,199)
height=c(80,34,56,34,98)
SAT=c(100,80,90,70,85)
SAT2=c(105,98,78,34,67)
introvert=c(3,4,NA,2,1)
DF=data.frame(id,age,gender,weight,height,SAT,SAT2,introvert,stringsAsFactors = TRUE)

grade <- function (x) {
  if (x>84){
    "Good"
  } else if (x>75){
    "So So"
  } else {
    "try again"
  }
}

我制作了这个数据框和这个 grade() 函数。

map(DF$SAT,grade) 工作正常,但如果我使用 map_int() 或 modify() 它永远不会工作。

map_int(DF$SAT,成绩)

错误:

Can't coerce element 1 from a character to a integer
modify(DF$SAT,grade)
Error: Can't coerce element 1 from a character to a double

问题是什么?

问题是后缀 (_int) 应该与 return 类型匹配。这里,grade 函数 return 是 character 而不是 integer 类型。如果我们需要returncharactervector,使用_chr

library(purrr)
map_chr(DF$SAT, grade)
[1] "Good"      "So So"     "Good"      "try again" "Good"  

?map 文档中提到了它

map_lgl(), map_int(), map_dbl() and map_chr() return an atomic vector of the indicated type (or die trying).

关于 modify 的错误,它在文档中说明

Unlike map() and its variants which always return a fixed object type (list for map(), integer vector for map_int(), etc), the modify() family always returns the same type as the input object.

因此,只有当输入和输出具有相同类型时它才有效

> modify(1:6, ~ .x + 1)
Error: Can't coerce element 1 from a double to a integer
> modify(1:6, ~ .x + 1L)
[1] 2 3 4 5 6 7
> modify(1:6, ~ .x + 1L)
[1] 2 3 4 5 6 7
> modify(1:6, ~ as.character(.x))
Error: Can't coerce element 1 from a character to a integer