0

I am trying to make a panel data with longitudinal data from Brazilian Central Bank, I am having trouble with arranging the dataframe in a panel data form,

Is there anyway to do it in R?

Here's my code so far:

install.packages("GetBCBData")
library(GetBCBData)

my.ids <- c(1475, 1490)

series.names <- c("sales_volume_index", "sales_vol_index_fuel")
names(my.ids) <- series.names

df <- gbcbd_get_series(id = my.ids, 
                       first.date = '2018-01-01',
                       last.date = Sys.Date(),
                       be.quiet = TRUE)
View(df)

Console output:

 ref.date     value       series.name
 01/01/2018    100     sales_volume_index
 01/02/2018    120     sales_volume_index
 01/03/2018    120     sales_volume_index
 01/01/2018    132     sales_vol_index_fuel
 01/02/2018    134     sales_vol_index_fuel
 01/03/2018    188     sales_vol_index_fuel

Expected output:

ref.date     sales_volume_index   sales_vol_index_fuel
01/01/2018        100                     132
01/02/2018        120                     134
01/03/2018        120                     188

AlSub
  • 1,384
  • 1
  • 14
  • 33

3 Answers3

3

A base R option can be reshape enabling wide option:

#Code
res <- reshape(df,idvar = 'ref.date',timevar = 'series.name',direction = 'wide')

Output:

    ref.date value.sales_volume_index value.sales_vol_index_fuel
1 01/01/2018                      100                        132
2 01/02/2018                      120                        134
3 01/03/2018                      120                        188
Duck
  • 39,058
  • 13
  • 42
  • 84
2

You can use the dcast() function in the reshape2 package.

dcast(df, ref.date ~ series.name, value.var="value")
Matthew Haas
  • 101
  • 7
1

You can use pivot_wider from the tidyr package:

tidyr::pivot_wider(df, values_from=value, names_from=series.name)