简体   繁体   中英

Creating vector in r based on values in another vector in a dataframe

I am very new to R and programming and have spent a lot of time trying to find the answer to this question without success. This is likely because I am not describing the problem well. I am trying to create a data frame in which the values in one vector are dependent on the prior element in the same column and the value of an element in the same position in a another column in the data frame. My output should look something like the following:

 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

My code to create this data frame is as follows:

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]
+       }
+  }

I am able to create the first three columns in the dataframe with the code above. However I am unable to populate the last column (int_inc). I receive a warning that "condition has length >1 and only the first element will be used". The vector data$int_inc is of Null value. In case it is not clear, I am attempting to increase the value of int_inc by 3% if the value of month is equal to 5 otherwise the value of the element equals that of the prior element.
Thanks very much for your help.

I would combine ifelse() and cumprod() to the same the effect as the loop

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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