如何使用for循环来创建和填充列?

2jcobegt  于 2023-04-03  发布在  其他
关注(0)|答案(2)|浏览(96)

我有一个简单的时间序列数据集,有10个变量-我想创建一个for循环(或函数),为时间序列中的每个变量(除了日期)创建一个“与上个月的变化”变量和“与上个月的百分比变化”变量。我知道我可以简单地为每个特定的列编写代码,但我想优化它,因为有很多列。
下面是我的数据的样子,“日期”,“销售额”,“价格”是一些列名:

+----+---+---+---+---+---+---+---+--
| Date       |   Sales   |  Price  | 
+----+---+---+---+---+---+---+---+--
| 01Aug2019  | 4         | 15      |
| 01Sept2019 | 6         | 30      |
| 01Oct2019  | 10        | 44      |
+----+---+---+---+---+---+---+---+--

下面是我希望使用for循环(或任何函数)后的效果

+----+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| Date       |   Sales   |  chg_Sales  | pct_chg_Sales |   Price |  chg_Price  | pct_chg_Price| 
+----+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 01Aug2019  | 4         | NA          |NA             |  15     | NA          |NA            |
| 01Sept2019 | 6         | 2           |50%            |  30     | 15          |100%          |
| 01Oct2019  | 10        | 4           |66%            |  44     | 14          |46%           |
+----+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

我尝试了下面的代码,但它不工作

add_column <- function (x, y){
  setDT (x)[,pct_chg_y:= (y - shift (y,1, type="lag")/shift (,1, type="lag")*100]

}
qf9go6mv

qf9go6mv1#

下面是data.table的一个选项,我们在.SDcols中指定感兴趣的列,通过从lag中减去.SD(数据表的子集)(即.SDshift)来创建“chg_”列,然后在第二步中,通过使用Mapshift除以“chg_”列来创建“pct_chg

nm1 <- c("Sales", "Price")
setDT(df1)[,  paste0("chg_", nm1)  :=  .SD - shift(.SD), .SDcols = nm1]
df1[, paste0("pct_chg_", nm1) :=   
      Map(function(x, y)  100 * (y/shift(x)), .SD, mget(paste0("chg_", nm1))),
               .SDcols = nm1]
df1
#         Date Sales Price chg_Sales chg_Price pct_chg_Sales pct_chg_Price
#1:  01Aug2019     4    15        NA        NA            NA            NA
#2: 01Sept2019     6    30         2        15      50.00000     100.00000
#3:  01Oct2019    10    44         4        14      66.66667      46.66667

数据

df1 <- structure(list(Date = c("01Aug2019", "01Sept2019", "01Oct2019"
), Sales = c(4, 6, 10), Price = c(15, 30, 44)), 
        class = "data.frame", row.names = c(NA, 
-3L))
agxfikkp

agxfikkp2#

library(dplyr)
library(scales)

df1 %>% 
  arrange(Date) %>% 
  mutate_at(.vars = c("Sales", "Price"), list(chg = ~(. - lag(.)),
                                              pct_chg = ~percent((. - lag(.))/lag(.))))

  #         Date Sales Price Sales_chg Price_chg Sales_pct_chg Price_pct_chg
  # 1 2019-08-01     4    15        NA        NA           NA%           NA%
  # 2 2019-09-01     6    30         2        15         50.0%        100.0%
  # 3 2019-10-01    10    44         4        14         66.7%         46.7%

相关问题