Unable to use a custom API call function within mutate

Hi, I tried to create a custom function to look up descriptions from diagnostic codes using a web service.

The function works if given a single input, but not if used within mutate. Does this have to do with it not being a vectorized function? This is beyond my depth. Any input appreciated!

library(tidyverse)
library(httr)

# Testing tibble
codes <- tibble::tribble(
                ~patient_id, ~icd_10_code,
                          1,    "L03.115",
                          2,     "G89.18",
                          3,   "T69.022A",
                          4,   "S78.119A",
                          5,    "L97.518"
)

# My function
ICD_description_API <- function(code) {
    url <- paste0("http://icd10api.com/?code=",code,"&desc=long&r=json")
    response <- GET(url)
    parsed_object <- jsonlite::fromJSON(
        content(
            response,
            as = "text"
        ), 
        simplifyVector = FALSE
    )
    return(parsed_object$Description)
}

# Works
ICD_description_API("T33.09XA")

# Doesn't work
codes %>%
    mutate(
        description = ICD_description_API(icd_10_code)
    )

yes, but you can use it rowwise

library(tidyverse)
library(httr)

# Testing tibble
codes <- tibble::tribble(
    ~patient_id, ~icd_10_code,
    1,    "L03.115",
    2,     "G89.18",
    3,   "T69.022A",
    4,   "S78.119A",
    5,    "L97.518"
)

# My function
ICD_description_API <- function(code) {
    url <- paste0("http://icd10api.com/?code=",code,"&desc=long&r=json")
    response <- GET(url)
    parsed_object <- jsonlite::fromJSON(
        content(
            response,
            as = "text"
        ), 
        simplifyVector = FALSE
    )
    return(parsed_object$Description)
}

# Works
ICD_description_API("T33.09XA")
#> [1] "Superficial frostbite of other part of head, initial encounter"

# Doesn't work
codes %>%
    rowwise() %>% 
    mutate(
        description = ICD_description_API(icd_10_code)
    )
#> # A tibble: 5 × 3
#> # Rowwise: 
#>   patient_id icd_10_code description                                            
#>        <dbl> <chr>       <chr>                                                  
#> 1          1 L03.115     Cellulitis of right lower limb                         
#> 2          2 G89.18      Other acute postprocedural pain                        
#> 3          3 T69.022A    Immersion foot, left foot, initial encounter           
#> 4          4 S78.119A    Complete traumatic amputation at level between unspeci…
#> 5          5 L97.518     Non-pressure chronic ulcer of other part of right foot…

Created on 2021-08-27 by the reprex package (v2.0.1)

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.