Sort of new R user here. I'm trying to decompose GDP series into trend and cycle using Hamilton's proposed filter I'm following the neverhpfilter package (https://github.com/JustinMShea/neverhpfilter?tab=readme-ov-file#readme)
This is my set up
library(OECD)
library(tidyr)
library(neverhpfilter)
library(lubridate)
gdp_data=get_dataset("QNA")
gdp_data=gdp_data[gdp_data$SUBJECT=="B1_GS1",]
gdp_data=gdp_data[gdp_data$MEASURE=="CQR",]
gdp_data=gdp_data[gdp_data$TIME_FORMAT=="P3M",]
gdp_data=gdp_data[,c(2,5,10)]
gdp_data$ObsValue=as.numeric(gdp_data$ObsValue)
gdp_growth=gdp_data%>%
group_by(LOCATION)%>%
mutate(growth=log(ObsValue)-dplyr::lag(log(ObsValue)))
gdp_growth$Time=yq(gdp_growth$Time)
gdp_growth=gdp_growth[gdp_growth$Time>="1991-04-01",]
gdp_growth$LOCATION <- countrycode(gdp_growth$LOCATION, origin = "iso3c", destination = "country.name")
colnames(gdp_growth)=c("country", "gdp_value", "date", "growth")
gdp_list=split(gdp_growth, gdp_growth$country)
countries_total=names(gdp_list)
filtered_gdp=list()
for (country_j in countries_total) {
country_temp=gdp_list[[country_j]]
country_temp_xts=as.xts(country_temp)
gdp_value=country_temp_xts[,c(2)]
country_temp_hf=yth_filter(100*log(gdp_value), h=8, p=4, output=c("x", "trend", "cycle"))
filtered_gdp[[country_j]]=country_temp_hf
}
I get an error saying that
Error in log(gdp_value) : non-numeric argument to mathematical function
But in the examples, the data used in the process is the same class as my data
class(country_temp_xts) [1] "xts" "zoo"
With
library(countrycode)was able to run most of your code, which was helpful.I believe the error has to do with the structure of your
xtsobject andgdp_valuebeing character and not numeric.Step-by-step, I believe this is what is happening in your
forblock:You start with this (using first Country as example, Australia):
Then
str(country_temp)would be:You will see that the data.frame includes the date, numeric
gdp_valueandgrowth, and character value ofcountry(a mix of different types).When you convert to
xtsobject:You have with
str(country_temp_xts):Note this has
Dataas character, not numeric. This is because these objects are matrices with ordered index attribute. You cannot mix types, which you can with a data.frame. If one column is character, then all will become character (similar to matrices).One option is to select your
gdp_valuewhich is the only value you are using, excluding the other character column, and then convert toxtsobject:Another approach, assuming you had a single character column, which you'd want to be numeric, is to use:
Let me know if this addresses your issue.