Home > database >  Error in spec : (df) : inherits(x,"tbl_df") is not true
Error in spec : (df) : inherits(x,"tbl_df") is not true

Time:06-21

Hi I am just trying to run a spec() on my df and keep running into this error

Error in spec(df) : inherits(x, "tbl_df") is not TRUE

I have absolutely no idea what it means, and my df is utterly unremarkable as far as I can tell.

Can someone please explain to me what the error means so that I can start troubleshooting?

Thanks!

CodePudding user response:

Quick answer: spec only works on tibbles of class spec_tbl_df.

There are several functions named spec(). You should mention that this one is from the readr package.

The documentation for readr::spec states:

spec() extracts the full column specification from a tibble created by readr.

In other words, it does not work on a regular data frame: it has to be a tibble and more than that, a tibble created by a readr function such as read_csv.

Some examples:

class(iris)
[1] "data.frame"

readr::spec(iris)
# not a tibble
Error in readr::spec(iris) : inherits(x, "tbl_df") is not TRUE

class(as_tibble(iris))
[1] "tbl_df"     "tbl"        "data.frame"
readr::spec(as_tibble(iris))
# it is a tibble but not created by readr
NULL

A fake example for a CSV file with 3 columns charge, old, new.

library(readr)
mydata <- read_csv("mydata.csv")
class(mydata)
[1] "spec_tbl_df" "tbl_df"      "tbl"         "data.frame" 

spec(mydata)
# now it works; it's a tibble with class spec_tbl_df
cols(
  charge = col_character(),
  old = col_double(),
  new = col_double()
)
  • Related