0

我需要一些帮助来创建一个在函数内部生成的数据帧,该函数对 R 中给定数据帧的每一行使用 for 循环。

总之,我的角色旨在促进数据质量流程,这是我在未来预测定价模型培训中的第一步。从这个意义上说,我们的数据库中有一些重要的经济变量,它们的时间频率不小于月份(例如巴西的肉类生产)。此外,您可能会注意到,在某些情况下,对于某些变量,几个月的值往往会重复,这在另一种情况下需要对我们的算法和模型进行适当的处​​理,以便以更高的统计精度来理解。

由于我们的目标具有每日时间性(价格),我想创建一个函数(month_to_daily()称为值),rnorm函数假设标准偏差 = 1。(我也接受对此进行改进的建议)

在这个工作阶段我可以简单地“每月”我的数据集来捕获每个月的最后一个值来进行推理研究,以及特征选择和因果顺序,但我被迫选择了这条更困难的路径由于我们需要在每个新的一天进行价格预测,或者每个新价格都已在我们的数据管道中注册并被我们的模型快速消耗和重新估计,因此每月随机转换数据。

因此,在您使用我的函数month_to_daily(monthly_dataset$variable, monthly_dataset$timestamp)(时间序列的类型等等。正是在这个阶段,我很难做到这一点。

接下来,我将描述代码块,我将在这些代码块中逐步演示,等待您对如何生成或填充data.frame在我的函数内部使用 for 循环创建的函数提出建议。

最初我加载了我打算使用的 R 包:

library(dplyr)
library(tidyverse)
library(fpp3)
library(lubridate)
library(xts)
library(zoo)
library(ggplot2)
library(plotly)

然后我加载我的示例数据:

monthly_dataset <- read.csv("https://github.com/rhozon/datasets/raw/master/dataset_monthly_faked_data.csv", head =TRUE, sep = "," ) %>%
  mutate(timestamp = yearmonth(Index),
         Index = as.Date(Index))
  
glimpse(monthly_dataset)

我们可以为我们的目的预览选定的时间序列:


ggplotly(
ggplot(monthly_dataset, aes(
                            x = timestamp,
                            y = br_meat_production
                            )) +
  geom_line()
)

然后通过创建将月度数据转换为具有可变性的每日数据的函数 ( month_to_daily),我有:

month_to_daily <- function( var, ref_month ){
  
  set.seed(123)
  
  for (i in 1:length(var)){
    
   daily_values <- 
    
    rnorm( 
      n = days_in_month(ref_month[i])-1, # days avaiable in each month
      
      mean = var[i], # values tend to be around oscilate the real values of each month
      
      sd = 1 # Rnd number generator with ~N(0,1)
     ) %>% # How can I put an if condition for integer or double for decimal rounding inside rnorm function ? cause selected variable is integer then, round to zero decimal values else use only two digits. 
     
   as.data.frame() %>% # How to populate it ?
     
   mutate(
     month_year = paste(month(ref_month[i]), "-" , year(ref_month[i]) ),
     month_year = gsub(" ", "", month_year )
     ) %>%
     
  rename(variable = ".") # How to put here the name of the user selected variable ?
   

 print(daily_values) 
 
 # Here is my difficult: How to generate an dataframe object inside the function results ?

  }
  
}

使用来自加载的示例数据集的数据的函数,我们有


br_meat_production_daily <- month_to_daily(monthly_dataset$br_meat_production, monthly_dataset$timestamp)

class(br_meat_production_daily) # Object created is NULL !

br_meat_production_daily例如,我如何设置数据框对象,包括第一列作为日期(标记),第二个使用month_year模拟值,第三个使用模拟值?也许在我可以调用ggplot2通过使用变量名称(在此对象中)与新创建的轨迹的日/月/年来绘制新生成的时间序列图之后。

为了更好地解释,我想要的输出是这样的:

请注意,我称为desired_df 的内容包含由我之前为br_meat_production 创建的函数的输出生成的值。

上图是函数生成的每日数据,下图是原始月值。

所以,鉴于我已经在这里一步一步地解释了我的步骤,从这个函数生成这个所需的数据帧的最佳建议是什么?那个月的几天?

4

0 回答 0