简体   繁体   中英

Sum columns as per condition in R

I have the following data frame

Accountnumber <- c("00650D-02876","00650D-02876")
Month <- c(1:14,1:20)
rate <- runif(n=1, min=1e-12, max=.9999999999)
df <- data.frame(Accountnumber,Month,rate)

For every account number, I have to sum up the rate of the first 12 months to get the 12mRate and I have to sum up the entire term of the account to get the TermRate. The term for each account is different, for eg here 00650D-02876 has a term of 14 ( month till 14 ) and 00650D-02877 has a term of 20 (month till 20 )

Expected Ouput

Accountnumber <- c("00650D-02876","00650D-02876")
rate_12 <- c(9.2716,9.2716)
TermRate <- c(10.8169,15.45282)
df2 <- data.frame(Accountnumber,rate_12,TermRate)

I propose this:

library(data.table)
setDT(df)
df[, rate_12 := .SD[1:12, .(sum(rate))], by = Accountnumber][, rate_term := sum(rate), by = Accountnumber][, .(rate_12 = first(rate_12),rate_term =  first(rate_term)), by = Accountnumber]

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