Fix incompatible type errors in R using dplyr / mutate

I am trying to use the tidyverse / dplyr package in R to work with data, including vectorized calls to the online API (from Altmetric), to add rows using mutate.

The smallest code I can create that reproduces the error is below. I get the error "Error: incompatible types awaiting a numeric vector"

library(tidyverse)
library(jsonlite)

fromJSON_wrapper <- function(x,y) {
  fromJSON(x)[[c(y)]]
}

toy <- tibble(
      doi = c("10.1002/anie.201500251", "10.1080/19443994.2015.1005695", "10.1007/s13721-015-0095-0"), 
      url = c("https://api.altmetric.com/v1/doi/10.1002/anie.201500251", "https://api.altmetric.com/v1/doi/10.1080/19443994.2015.1005695", "https://api.altmetric.com/v1/doi/10.1080/19443994.2015.1005695")
      )

extracted <- toy %>% rowwise() %>% mutate(score = fromJSON_wrapper(url,"score"))

The code for extracting one point below works, whether using a wrapper or a single line, and I'm not sure why my code is not working.

fromJSON_wrapper("https://api.altmetric.com/v1/doi/10.1007/s13721-015-0095-0")
extracted <- toy[1,] %>% rowwise() %>% mutate(score = fromJSON_wrapper(url, "score"))

Any suggestions would be appreciated.

+4
source share
1 answer

URL , . purrr::map_dbl , sapply .

library(tidyverse)

toy <- tibble(
    doi = c("10.1002/anie.201500251", "10.1080/19443994.2015.1005695", "10.1007/s13721-015-0095-0"), 
    url = c("https://api.altmetric.com/v1/doi/10.1002/anie.201500251", "https://api.altmetric.com/v1/doi/10.1080/19443994.2015.1005695", "https://api.altmetric.com/v1/doi/10.1080/19443994.2015.1005695")
)

extracted <- toy %>% mutate(score = map_dbl(url, ~jsonlite::fromJSON(.x)$score))

extracted %>% select(doi, score)
#> # A tibble: 3 × 2
#>                             doi score
#>                           <chr> <dbl>
#> 1        10.1002/anie.201500251  0.25
#> 2 10.1080/19443994.2015.1005695  1.00
#> 3     10.1007/s13721-015-0095-0  1.00
+3

Source: https://habr.com/ru/post/1676410/


All Articles