stevec
stevec

Reputation: 52468

cannot coerce class ‘c("fseq", "function")’ to a data.frame

This produces a 1 column data.frame:


library(tidyverse)
library(jsonlite)
library(purrr)

symbols <- 'https://api.exchangerate.host/symbols' %>% fromJSON %>% .$symbols

symbols %>% 
  {
  data.frame(code = map_chr(., ~ .x$code ) %>% unname)
  }
# 1 column data.frame:
#     code
# 1    AED
# 2    AFN
# 3    ALL
# 4    AMD

Yet this errors

symbols %>% 
  {
  data.frame(code = . %>% map_chr(~ .x$code ) %>% unname)
  }
 # Error in as.data.frame.default(x[[i]], optional = TRUE) : 
 #  cannot coerce class ‘c("fseq", "function")’ to a data.frame

Why does piping to purrr::map_chr() error, and how can we get it to work?

Upvotes: 2

Views: 338

Answers (2)

akrun
akrun

Reputation: 887501

It is not giving any error message, but just 0 row data.frame with the OP's code. If we want to do this with the same code as OP's, then wrap the . with {}

symbols %>%
     {data.frame(code = {.} %>% 
                 map_chr(~ .x$code ) %>% 
                 unname)} %>%
    head
#  code
#1  AED
#2  AFN
#3  ALL
#4  AMD
#5  ANG
#6  AOA

Or it can be done in a more easier way with bind_rows and select the 'code' column so that we can do this in a single package (dplyr) and avoid any looping with map (from purrr)

library(dplyr)
symbols %>% 
     bind_rows %>%
     select(code)
# A tibble: 171 x 1
#   code 
#   <chr>
# 1 AED  
# 2 AFN  
# 3 ALL  
# 4 AMD  
# 5 ANG  
# 6 AOA  
# 7 ARS  
# 8 AUD  
# 9 AWG  
#10 AZN  
# … with 161 more rows

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389125

I don't get that error message but I get 0 row dataframe. Try this :

symbols %>% 
{
   data.frame(code = purrr::map_chr(., ~.x$code) %>% unname())
}

Perhaps, this is more cleaner :

symbols %>% map_chr(~.x$code ) %>% unname %>% data.frame(code = .)

Upvotes: 1

Related Questions