0

Here is my code. I have two questions about my codes. The first question is what's the difference between these two classes? The second question is why I must use as_tibble() function so that I could use pivot_wider() function?

head(global_economy)
write.table(global_economy,"global_economy.csv",sep=",",row.names=FALSE)
class(global_economy)

Country Code    Year    GDP Growth  CPI Imports Exports Population
Afghanistan AFG 1960    537777811   NA  NA  7.024793    4.132233    8996351
Afghanistan AFG 1961    548888896   NA  NA  8.097166    4.453443    9166764
Afghanistan AFG 1962    546666678   NA  NA  9.349593    4.878051    9345868
Afghanistan AFG 1963    751111191   NA  NA  16.863910   9.171601    9533954
Afghanistan AFG 1964    800000044   NA  NA  18.055555   8.888893    9731361
Afghanistan AFG 1965    1006666638  NA  NA  21.412803   11.258279   9938414

'tbl_ts' 'tbl_df' 'tbl' 'data.frame'

wider_tibble <- global_economy %>%
as_tibble()%>%
pivot_wider(names_from=Country,values_from=GDP)
class(wider_tibble)

'tbl_df' 'tbl' 'data.frame'
rawr
  • 20,481
  • 4
  • 44
  • 78
  • `pivot_wider` will work on dataframe objects. It doesn't necessarily need to be a tibble object. – LMc May 18 '21 at 03:45
  • If I remove the row(as_tibble()%>%) , the code will return an error. – Xiangyuan Lee May 18 '21 at 03:46
  • Just to show you, I've temporarily posted an answer. This does not throw an error. What is the error you are getting? Otherwise, note that `pivot_wider(iris)` does not throw an error and `class(iris)` is "data.frame". I'm guessing there is something else in your code causing your problem. – LMc May 18 '21 at 03:55
  • There is an error, which showed it's not a valid tsibble. wider_tibble <- global_economy %>% pivot_wider(names_from=Country,values_from=GDP) class(wider_tibble) Error: The result is not a valid tsibble. i Do you need `as_tibble()` to work with data frame? Traceback: – Xiangyuan Lee May 18 '21 at 04:08
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick May 18 '21 at 05:13

1 Answers1

3

My guess: The first one is a time_series ('table_ts'). 'as_tibble' returns it to a dataframe without time series elements so that 'pivot_wider' works.

TarJae
  • 72,363
  • 6
  • 19
  • 66