bit_entropy
bit_entropy

Reputation: 41

fixing incompatible types error in R using dplyr/mutate

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

The smallest code I can create that reproduces the error is that below. I get the error "Error: incompatible types, expecting 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 a single score below works, whether just using the wrapper or on a one row tibble and I'm not sure why my code isn't 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.

Upvotes: 4

Views: 1836

Answers (1)

alistaire
alistaire

Reputation: 43334

It's simpler to just iterate over the vector of URLs and extract what you need. purrr::map_dbl makes this simple, though sapply would work fine, too.

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

Upvotes: 3

Related Questions