【问题标题】:Run Moving Average Accross Multiple Columns - R跨多列运行移动平均线 - R
【发布时间】:2020-02-19 17:15:08
【问题描述】:

我正在寻找一种方法来为我的数据框中的每一列执行移动平均计算并将结果附加到原始数据框中

R 没有循环所有列给我这个我不明白的错误

2: 在 if (type == "s") { : 条件的长度 > 1 并且只有 将使用第一个元素 3:在 colnames(temp_df)[1]

我了解 for 循环适用于逻辑元素,但我不知道如何使用循环解决此问题。

    library(lubridate)
    library(pracma)
    library(dplyr)

  # ---- Fake Data Frame

    date       a         b         c                  d                         e
    01/01/2018 0.2087381 0.2892251 0.003478307        0.1186026                 0
    02/01/2018 0.3213273 0.4482369 0.005533266        0.2137506                 0
    03/01/2018 0.2516612 0.3508488 0.004430171        0.1671371                 0
    04/01/2018 0.2436500 0.3375996 0.004323420        0.1580058                 0
    05/01/2018 0.2542939 0.3509883 0.004421275        0.1621509                 0
    06/01/2018 0.2385525 0.3277567 0.004154398        0.1676672                 0


        #add index to allow merge after looping
        rawData <- rawData %>%
          mutate(index = row_number())


        for (i in colnames(rawData)) {

          #define the column in the loop
          data <- rawData[, i]

          #transform to data series
          ts_data <- ts(data, frequency = 365)

          #create mvg avg
          ts_data_mvgavg <- movavg(ts_data,n=7)

          #store result in a data frame
          temp_df <- as.data.frame(ts_data_mvgavg)

          #create a row index to allow merge with raw data
          temp_df <- temp_df %>%
            mutate(index = row_number())

          #define new column name based on variable
          new_colname <- paste0("mvg_avg_", i)

          #rename the column so that it's unique
          colnames(temp_df)[1]<- new_colname

          #merge temp_df and rawData dataframe
          main_DF <- merge(rawData, temp_df, by.x = "index", by.y = "index")

        }

【问题讨论】:

  • @akrun 我用实际数据更新了数据框。整个数据框包含 1 年的数据

标签: r for-loop


【解决方案1】:

修正了问题中的输入数据,我们cbind输入到它的滚动平均值。

library(zoo)
rawData <- data.frame(a = 101:465, b = 1001:1365, c = 1:365) # test data

rawData2 <- cbind(rawData, roll = rollmeanr(rawData, 7, fill = NA))

给予:

     a    b  c roll.a roll.b roll.c
1  101 1001  1     NA     NA     NA
2  102 1002  2     NA     NA     NA
3  103 1003  3     NA     NA     NA
4  104 1004  4     NA     NA     NA
5  105 1005  5     NA     NA     NA
6  106 1006  6     NA     NA     NA
7  107 1007  7    104   1004      4
8  108 1008  8    105   1005      5
9  109 1009  9    106   1006      6
10 110 1010 10    107   1007      7
11 111 1011 11    108   1008      8
12 112 1012 12    109   1009      9
... etc ...

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2017-09-01
    • 2013-12-22
    • 2018-10-21
    • 2016-05-16
    • 2020-02-04
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多