在R中将每月数据转换为每日数据

在R中将每月数据转换为每日数据

本文介绍了在R中将每月数据转换为每日数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个data.frame df,其中包含每月数据:

I have a data.frame df that has monthly data:

Date           Value
2008-01-01      3.5
2008-02-01      9.5
2008-03-01      0.1

我希望每个月的每一天都有数据(并且我假设Value在每个月都不会改变),因为我会将其合并到另一个包含月度数据的表中.

I want there to be data on every day in the month (and I will assume Value does not change during each month) since I will be merging this into a different table that has monthly data.

我希望输出看起来像这样:

I want the output to look like this:

Date           Value
2008-01-02      3.5
2008-01-03      3.5
2008-01-04      3.5
2008-01-05      3.5
2008-01-06      3.5
2008-01-07      3.5
2008-01-08      3.5
2008-01-09      3.5
2008-01-10      3.5
2008-01-11      3.5
2008-01-12      3.5
2008-01-13      3.5
2008-01-14      3.5
2008-01-15      3.5
2008-01-16      3.5
2008-01-17      3.5
2008-01-18      3.5
2008-01-19      3.5
2008-01-20      3.5
2008-01-21      3.5
2008-01-22      3.5
2008-01-23      3.5
2008-01-24      3.5
2008-01-25      3.5
2008-01-26      3.5
2008-01-27      3.5
2008-01-28      3.5
2008-01-29      3.5
2008-01-30      3.5
2008-01-31      3.5
2008-02-01      9.5

我尝试了 to.daily ,但是我的电话是

I have tried to.daily but my call:

df<-to.daily(df $ Date)

返回

to.period(x,"days",name = name,...)中的错误:"x"不包含数据

推荐答案

to.daily 只能应用于 xts/zoo 对象,并且只能转换为LOWER频率.即从每天到每月,但并非相反.一种简单的方法来完成您想要的是将 df 转换为 xts 对象:

to.daily can only be applied to xts/zooobjects and can only convert to a LOWER frequency. i.e. from daily to monthly, but not the other way round.One easy way to accomplish what you want is converting df to an xts object:

df.xts <- xts(df$Value,order.by = df$Date)

然后合并,就像这样:

na.locf(merge(df.xts, foo=zoo(NA, order.by=seq(start(df.xts), end(df.xts),
  "day",drop=F)))[, 1])
               df.xts
2018-01-01    3.5
2018-01-02    3.5
2018-01-03    3.5
2018-01-04    3.5
2018-01-05    3.5
2018-01-06    3.5
2018-01-07    3.5
….
2018-01-27    3.5
2018-01-28    3.5
2018-01-29    3.5
2018-01-30    3.5
2018-01-31    3.5
2018-02-01    9.5
2018-02-02    9.5
2018-02-03    9.5
2018-02-04    9.5
2018-02-05    9.5
2018-02-06    9.5
2018-02-07    9.5
2018-02-08    9.5
….
2018-02-27    9.5
2018-02-28    9.5
2018-03-01    0.1

如果您要在一个月内连续调整价格,请使用 na.spline 代替 na.locf .

If you want to adjust the price continuously over the course of a month use na.spline in place of na.locf.

这篇关于在R中将每月数据转换为每日数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 19:51