R:如何计算列中元素的每日数据的年平均值和其他操作 [英] R: How to calculate year-wise mean and other operations on daily data for elements in a column

查看:486
本文介绍了R:如何计算列中元素的每日数据的年平均值和其他操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮我。我被困了很长时间。我是一个R初学者,我想知道如何使用多个索引对数据框元素执行操作。公司和时间如下面的情况下优雅?我想对每个公司的一些其他变量执行一些典型的操作,例如年平均值,这里是一个例子:
我想从所有公司的变量A和F的日常数据计算年平均值在数据集中。这是我的数据集。我使用了dplyr和hydroTSM包。以下是我的代码:

Please help me out. I have been stuck for a long time. I am an R beginner, and I want to know how to perform operations on data frame elements using multiple indices e.g. firms and time as in the below case elegantly? I want to perform some typical operations e.g year-wise mean on some other variables for each firm, and here is an example: I am want to calculate year-wise mean from daily data of variables A and F for all firms in the dataset. This is my dataset. I have used dplyr and hydroTSM packages. Following is my code:

MeanA<- df %>% select(Firm, Date, A,) %>% group_by(Firm) %>% do(daily2annual(., A, FUN=mean, na.rm = TRUE, out.fmt="%Y", dates = 2))

它返回以下错误:

Error in eval(expr, envir, enclos) : argument is missing, with no default

data.table包中添加了一个年份列。代码:

I have also tried the data.table package with adding an additional Year column. Code:

MeanA <- df[ , A, by = "Firm" & "Year"]

结果:

Error in `[.data.frame`(df, , A, by = "Firm" & "Year") : unused argument(by = "Firm" & "Year")

请建议一个出路(有或没有dplyr)。平均值表以及其他计算的年度值, 是使用plm包进行面板回归分析的输入。 提前感谢。

Please suggest a way out (with or without dplyr). The table of means, as well as other year-wise values I would be calculating, is input for panel regression analysis using plm package. Thanks in advance.

推荐答案

这不是一个漂亮的答案,但我厌倦了工作。如果你想要公司的年平均值,我从日期字段提取年份,然后在 aggregate 函数中使用它。

Well this isn't a pretty answer but I'm tired of working at it. If you want the yearly mean by firm, I extracted the year from the date field and then used this in the aggregate function.

df$Date = as.Date(df$Date, "%m/%d/%Y")
df$F = as.numeric(df$F)
df$Year = as.Date(paste(substr(df$Date, 1, 4), "1", "1",sep="-"), "%Y-%m-%d")
newDat = aggregate(cbind(A, E, F) ~ Firm + Year, df, FUN = mean)

这篇关于R:如何计算列中元素的每日数据的年平均值和其他操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆