Проблема в том, что столбец HPI
был преобразован в коэффициент при замене формата периода на gsub
. Поэтому вам необходимо преобразовать его обратно в цифру c. Попробуйте это:
library(dplyr)
library(lubridate)
set.seed(42)
# Example data
quarters <- paste0("T", c(1:4))
years <- c("2019", "2020")
dates <- c(paste0(years[[1]], quarters), paste0(years[[2]], quarters))
df_HPI <- data.frame(
Periodo = rep(dates, 2),
CCAA = c(rep("Region1", 8), rep("Region2", 8)),
HPI = runif(16)
)
head(df_HPI)
#> Periodo CCAA HPI
#> 1 2019T1 Region1 0.9148060
#> 2 2019T2 Region1 0.9370754
#> 3 2019T3 Region1 0.2861395
#> 4 2019T4 Region1 0.8304476
#> 5 2020T1 Region1 0.6417455
#> 6 2020T2 Region1 0.5190959
# Replace period format
df_HPI <- data.frame(sapply(df_HPI, function(x) {gsub("T1","-01-01",x)})) # Q1
df_HPI <- data.frame(sapply(df_HPI, function(x) {gsub("T2","-04-01",x)})) # Q2
df_HPI <- data.frame(sapply(df_HPI, function(x) {gsub("T3","-07-01",x)})) # Q3
df_HPI <- data.frame(sapply(df_HPI, function(x) {gsub("T4","-10-01",x)})) # Q4
# Convert column into a date
df_HPI$Periodo <- as.Date(df_HPI$Periodo)
# Problem: HPI was converted to a factor
class(df_HPI$HPI)
#> [1] "factor"
# Solution: Convert back to numeric
df_HPI$HPI <- as.numeric(as.character(df_HPI$HPI))
# Aggregate to annual data
df_HPI %>%
mutate(Year=year(Periodo),
Quarter=quarter(Periodo),
Finyear = ifelse(Quarter <= 2, Year, Year+1)) %>%
group_by(Finyear, CCAA) %>%
summarise(HPIy=mean(HPI))
#> # A tibble: 6 x 3
#> # Groups: Finyear [3]
#> Finyear CCAA HPIy
#> <dbl> <fct> <dbl>
#> 1 2019 Region1 0.926
#> 2 2019 Region2 0.681
#> 3 2020 Region1 0.569
#> 4 2020 Region2 0.592
#> 5 2021 Region1 0.436
#> 6 2021 Region2 0.701
Создано в 2020-04-04 пакетом Представить (v0.3.0)