yoo
yoo

Reputation: 511

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"
  }
}

I made this data frame, and this grade() function.

map(DF$SAT,grade) works fine, but it never works if I use map_int() or modify().

map_int(DF$SAT,grade)

Error:

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

What is the problem?

Upvotes: 1

Views: 59

Answers (2)

KidoShinji
KidoShinji

Reputation: 1

I met similar issues. My first finding is that modify works on a data frame instead of a matrix. So, I tried

modify(DF["SAT"],grade)

And I got an error message:

Error in if (x > 84) { : the condition has length > 1

Finally I tried

modify(DF["SAT"],~ifelse(. > 84, "Good", ifelse(.>75, "So So", "try again")))

It works.

        SAT
1      Good
2     So So
3      Good
4 try again
5      Good

Upvotes: 0

akrun
akrun

Reputation: 887511

The issue is that the suffix (_int) should match the return type. Here, the grade function returns a character and not integer type. If we need to return the character vector, use _chr

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

It is mentioned in the ?map documentation

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

Regarding the error with modify, it states in documentation

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.

Thus, it works only if the input and output have the same type

> 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

Upvotes: 2

Related Questions