r - 从 data.frame 中的现有变量创建几个新的派生变量

标签 r variables dataframe

在 R 中,我有一个 data.frame,其中包含数年来每月测量的多个变量。我想得出每个变量的月平均值(使用所有年份)。理想情况下,这些新变量将全部放在一个新的 data.frame 中(继承 ID),下面我只是将新变量添加到 data.frame 中。目前我知道如何做到这一点的唯一方法(如下)似乎相当费力,我希望在 R 中可能有一种更聪明的方法来做到这一点,不需要像我下​​面那样输入每个月和变量。

# Example data.frame with only two years, two month, and two variables
# In the real data set there are always 12 months per year 
# and there are at least four variables
df<- structure(list(ID = 1:4, ABC.M1Y2001 = c(10, 12.3, 45, 89), ABC.M2Y2001 = c(11.1, 
          34, 67.7, -15.6), ABC.M1Y2002 = c(-11.1, 9, 34, 56.5), ABC.M2Y2002 = c(12L,
          13L, 11L, 21L), DEF.M1Y2001 = c(14L, 14L, 14L, 16L), DEF.M2Y2001 = c(15L,
          15L, 15L, 12L), DEF.M1Y2002 = c(5, 12, 23.5, 34), DEF.M2Y2002 = c(6L,
          34L, 61L, 56L)), .Names = c("ID", "ABC.M1Y2001", "ABC.M2Y2001","ABC.M1Y2002", 
          "ABC.M2Y2002", "DEF.M1Y2001", "DEF.M2Y2001", "DEF.M1Y2002", 
          "DEF.M2Y2002"), class = "data.frame", row.names = c(NA, -4L))


# list variable to average for ABC Month 1 across years
ABC.M1.names <- c("ABC.M1Y2001", "ABC.M1Y2002") 
df <- transform(df,  ABC.M1 = rowMeans(df[,ABC.M1.names], na.rm = TRUE))

# list variable to average for ABC Month 2 across years
ABC.M2.names <- c("ABC.M2Y2001", "ABC.M2Y2002") 
df <- transform(df,  ABC.M2 = rowMeans(df[,ABC.M2.names], na.rm = TRUE))

# and so forth for ABC
# ...

# list variables to average for DEF Month 1 across years
DEF.M1.names <- c("DEF.M1Y2001", "DEF.M1Y2002") 
df <- transform(df,  DEF.M1 = rowMeans(df[,DEF.M1.names], na.rm = TRUE))

# and so forth for DEF
# ...

最佳答案

这是使用 data.table 的解决方案开发版v1.8.11 (其中为 data.table 实现了 meltcast 方法):

require(data.table)
require(reshape2) # melt/cast builds on S3 generic from reshape2
dt <- data.table(df) # where df is your data.frame
dcast.data.table(melt(dt, id="ID")[, sum(value)/.N, list(ID, 
        gsub("Y.*$", "", variable))], ID ~ gsub)
   ID ABC.M1 ABC.M2 DEF.M1 DEF.M2
1:  1  -0.55  11.55   9.50   10.5
2:  2  10.65  23.50  13.00   24.5
3:  3  39.50  39.35  18.75   38.0
4:  4  72.75   2.70  25.00   34.0

您只需 cbind这是您的原始数据。

请注意sum是一个原语,其中 mean是S3通用的。因此,使用 sum(.)/length(.)更好(就好像分组太多一样,为每个组使用 mean 调度正确的方法可能是一项相当耗时的操作)。 .N是 data.table 中的一个特殊变量,它直接给出组的长度。

关于r - 从 data.frame 中的现有变量创建几个新的派生变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19862384/

相关文章:

variables - 如何正确命名代表值 1 - n 的变量?

c# - 如何在 Unity3D 中保存自定义变量?

r - 删除列表中数据框中的一列

r - Shiny 的 session 中止

python - 为什么 Python 和 R 有两个不同的归一化结果

r - 使用 as.yearmon 时 Pivot Wider 导致问题

dataframe - 将数据帧 Julia 中每一列中的缺失值替换为平均值

r - 将数据导出到 Excel 工作表中的特定单元格

java - android处理程序将变量设置为final

python - 从 pandas groupby 中的每个组中选择前 n 个元素