繁体   English   中英

基于数据帧中另一个向量中的值在r中创建向量

[英]Creating vector in r based on values in another vector in a dataframe

我对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,只使用第一个元素”。 向量数据$ int_inc的值为Null。 如果不清楚,如果month的值等于5,我试图将int_inc的值增加3%,否则元素的值等于previous元素的值。
非常感谢您的帮助。

我会将ifelse()cumprod()与循环结合起来

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM