UseR10085
UseR10085

Reputation: 8176

Calculation from a formula using tidyverse in R

I want to calculate the following indices using tidyverse package in R.

enter image description here

enter image description here

enter image description here

where rm is Monthly rainfall in month m, m = 1,2,3………12

To achieve this I am using the following code

library(tidyverse) 
library(seas) 
library(openxlsx)
library(lubridate)

## get mscdata from "seas" packages
data(mscdata)
dat <- (mksub(mscdata, id=1108447))

Monthly <- dat %>% 
  mutate(Year = year(date),
         Month = month(date),
         Day = day(date)) %>% 
  group_by(Year, Month) %>% 
  summarise(Monthly = sum(precip)) 

Monthly %>% 
  group_by(Year) %>% 
  summarise(Rk = sum(Monthly),
            Ck = (1/Rk)*sum(Month*Monthly),
            Zk = sqrt((1/Rk)*sum(Month-Ck)^2*Monthly))

The calculation of Rk and Ck is matching with excel calculation. But the values of Zk is not matching. What mistake I am committing?

Upvotes: 0

Views: 274

Answers (2)

awaji98
awaji98

Reputation: 685

To match your Excel figures, you need to add a pair of parentheses:

Monthly %>% 
  group_by(Year) %>% 
  summarise(Rk = sum(Monthly),
            Ck = (1/Rk)*sum(Month*Monthly),
            Zk = sqrt((1/Rk)*sum(((Month-Ck)^2)*Monthly)))

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389055

Calculated the sum too early.

library(dplyr)

Monthly %>% 
  group_by(Year) %>% 
  summarise(Rk = sum(Monthly),
            Ck = (1/Rk)*sum(Month*Monthly),
            Zk = sqrt((1/Rk)*sum((Month-Ck)^2*Monthly)))

#   Year     Rk     Ck     Zk
#1  1975 1320.1 7.4674 4.1455
#2  1976 1008.3 5.5078 3.8184
#3  1977 1032.3 7.4917 3.8336
#4  1978 1016.8 6.3460 3.7901
#5  1979  986.2 7.4500 4.1851
#6  1980 1418.5 7.2960 3.9661
#7  1981 1459.2 7.0578 3.7275
#8  1982 1260.1 6.0253 4.2520
#9  1983 1489.5 6.2925 4.0069
#...
#...

Upvotes: 3

Related Questions