【问题标题】:Creating vector in r based on values in another vector in a dataframe根据数据框中另一个向量中的值在 r 中创建向量
【发布时间】:2013-12-03 21:23:27
【问题描述】:

我对 R 和编程非常陌生,并且花了很多时间试图找到这个问题的答案,但没有成功。这可能是因为我没有很好地描述这个问题。我正在尝试创建一个数据框,其中一个向量中的值取决于同一列中的前一个元素以及数据框中另一列中相同位置的元素的值。我的输出应该如下所示:

 dates       month   increase    int_inc
 2010-01-01  1   1       1
 2010-02-01  2   1.03    1
 2010-03-01  3   1.061   1
 2010-04-01  4   1.093   1
 2010-05-01  5   1.126   1.03
 2010-06-01  6   1.159   1.03
 2010-07-01  7   1.194   1.03
 2010-08-01  8   1.23    1.03
 2010-09-01  9   1.267   1.03
 2010-10-01  10  1.305   1.03
 2010-11-01  11  1.344   1.03
 2010-12-01  12  1.384   1.03
 2011-01-01  1   1.426   1.03
 2011-02-01  2   1.469   1.03
 2011-03-01  3   1.513   1.03
 2011-04-01  4   1.558   1.03
 2011-05-01  5   1.605   1.061
 2011-06-01  6   1.653   1.061
 2011-07-01  7   1.702   1.061
 2011-08-01  8   1.754   1.061
 2011-09-01  9   1.806   1.061
 2011-10-01  10  1.86    1.061
 2011-11-01  11  1.916   1.061
 2011-12-01  12  1.974   1.061

我创建这个数据框的代码如下:

dates <- c(seq(as.Date("2010-01-01"), as.Date("2012-01-01"), by = "+1 month"))
month <- c(as.numeric(format(dates, "%m")))
data <- data.frame(dates, month)
Len  <- length(data$month)-1
data$increase <- 1 * 1.03 ^ (0:len)

data$int_inc <- for (i in 1:Len) {
+           data$int_inc[1] <- 1
+          if ( data$month == 5) {
+          data$int_inc[i+1] <- data$int_inc[i] *    1.03
+         } else {
+          data$int_inc[i+1] <- data$int_inc[i]
+       }
+  }

我可以使用上面的代码在数据框中创建前三列。但是我无法填充最后一列(int_inc)。我收到一条警告“条件的长度 > 1,并且只会使用第一个元素”。向量 data$int_inc 为 Null 值。如果不清楚,如果月份的值等于 5,我会尝试将 int_inc 的值增加 3%,否则元素的值等于前一个元素的值。
非常感谢您的帮助。

【问题讨论】:

  • 不用看太仔细,需要data$month[i] == 5吗?

标签: r


【解决方案1】:

我会结合ifelse()cumprod() 来达到与循环相同的效果

month <- rep(1:12, 5)
int_inc <- cumprod(ifelse(month == 5, 1.03, 1))

【讨论】:

    【解决方案2】:
    data$int_inc <-  1.03 ^ ( cumsum(month==5)  )
    

    【讨论】:

    • 1 * 什么都不做。
    • 我的懒惰。我只是修改了“用户”用于他的“增加”构造的原始代码。
    猜你喜欢
    • 2021-07-26
    • 1970-01-01
    • 2012-03-13
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多