r - 如何迭代创建列?

标签 r dplyr data.table

这是我的数据示例;

df <- structure(list(Product = c("A", "A", "A", "A", "A"), Month = 8:12, 
    Real = c(1550L, 2238L, 1534L, 726L, 255L), coef = c(0.9503, 
    0.9503, 0.9503, 0.9503, 0.9503)), row.names = c(NA, -5L), class = c("data.table", 
"data.frame"))

我需要为每行计算一个常量(名为 Bias),并使用 BiasIter 列创建列。

如果没有什么意义,这就是我的做法;

df %>% 
mutate(Iter1 = ceiling(coef*Real)) %>% 
mutate(Bias1 = c(0,((Real[1] - Iter1[1])/Real[1]),rep(0,n() - 2))) %>% 
mutate(Iter2 = ceiling(Iter1*(1 + Bias1))) %>% 
mutate(Bias2 = c(0,0,((Real[2] - Iter2[2])/Real[2]),rep(0,n() - 3))) %>% 
mutate(Iter3 = ceiling(Iter2*(1 + Bias2))) %>% 
mutate(Bias3 = c(0,0,0,((Real[3] - Iter3[3])/Real[3]),rep(0,n() - 4))) %>% 
mutate(Iter4 = ceiling(Iter3*(1 + Bias3))) %>% 
mutate(Bias4 = c(0,0,0,0,((Real[4] - Iter4[4])/Real[4]),rep(0,n() - 5))) %>% 
mutate(Iter5 = ceiling(Iter4*(1 + Bias4))) %>% 
select(-contains('Bias'))

我无法在任何地方适应这种丑陋且硬编码的东西,因为这样的表太多,而且行数不同,这意味着我必须为每个表创建的列数不同。

我正在努力使其通用。

这是我想要的输出;

  Product Month  Real  coef Iter1 Iter2 Iter3 Iter4 Iter5
  <chr>   <int> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 A           8  1550 0.950  1473  1473  1473  1473  1473
2 A           9  2238 0.950  2127  2233  2233  2233  2233
3 A          10  1534 0.950  1458  1458  1462  1462  1462
4 A          11   726 0.950   690   690   690   723   723
5 A          12   255 0.950   243   243   243   243   245

提前致谢。

最佳答案

可以使用for循环的递归使用

coef <- df$coef
 real <- df$Real
 for(i in seq_len(nrow(df))) {
 
     
      if(i == 1) {
        iter <- ceiling(coef* real)
        df[, paste0('Iter', i) := iter]
        bias <- c(rep(0, i),(( real[i]- iter[i])/real[i]),
              rep(0, nrow(df) - (i + 1)))
        df[, paste0("Bias", i) := bias]
      
      
      } else {
           
        iter <-  ceiling(df[[paste0('Iter', i-1)]]*(1 +
              df[[paste0('Bias', i-1)]]))
         df[, paste0('Iter', i) := iter]
         if(i < 5) {
           bias <- c(rep(0, i), ((real[i] - 
           df[[paste0('Iter', i)]][i])/real[i]),rep(0, nrow(df) - (i +1) ))
           df[, paste0("Bias", i) := bias]
           }
      
      }
 
 
}

df[, paste0("Bias", 1:4) := NULL]

-输出

> df
   Product Month  Real   coef Iter1 Iter2 Iter3 Iter4 Iter5
    <char> <int> <int>  <num> <num> <num> <num> <num> <num>
1:       A     8  1550 0.9503  1473  1473  1473  1473  1473
2:       A     9  2238 0.9503  2127  2233  2233  2233  2233
3:       A    10  1534 0.9503  1458  1458  1462  1462  1462
4:       A    11   726 0.9503   690   690   690   723   723
5:       A    12   255 0.9503   243   243   243   243   245

关于r - 如何迭代创建列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71887393/

相关文章:

r - 使用具有多个 value.var 的 dcast 时出错

r - 对于每一列,按组在之前的时间窗口内对分数进行求和

r - 从坐标获取近似大陆

R dplyr : dealing with NA values and empty/missing rows when summarizing data by group

R:频率计数,但每个类别都在单独的列中

r - 找到一对列中的最大值/最小值

r - 计算在给定级别发生变化时花费的时间

r - 绘制两条曲线之间的阴影区域

r - r中的NA值总和

r - 修改逻辑回归中的因子名称