I think i calculated correctly the average distance between three consequtive values when the condition (described in the code) is met. However, i did this calculation only for a single year and i don’ t know how to do it for every year. Could you please help me? I think i need another for loop but i when i tried this i failed.
<code>seed(123)
years <- rep(2010:2014, each = 365)
months <- rep(rep(1:12, each = 31), 5)[1:(5 * 365)]
days <- rep(1:31, times = 5 * 12)[1:(5 * 365)]
# Create a data frame with year, month, day,
x <- rnorm(5 * 365, mean = 15, sd = 5)
df <- data.frame(Year = years, Month = months, Day = days, Values = x)
df_filt = df %>% filter(Year==2010)
df_filt$Distance <- NA
for(i in 3:nrow(df_filt)) {
if (df_filt$Values[i] > df_filt$Values[i-1] && df_filt$Values[i-1] > df_filt$Values[i-2]) {
df_filt$Distance[i] =
(1/3)*(sqrt((df_filt$Values[i] - df_filt$Values[i-2])^2) +
sqrt((df_filt$Values[i] - df_filt$Values[i-1])^2) +
sqrt((df_filt$Values[i-2] - df_filt$Values[i-1])^2))
}
else{
df_filt$Distance[i] <- NA
}
}
</code>
<code>seed(123)
years <- rep(2010:2014, each = 365)
months <- rep(rep(1:12, each = 31), 5)[1:(5 * 365)]
days <- rep(1:31, times = 5 * 12)[1:(5 * 365)]
# Create a data frame with year, month, day,
x <- rnorm(5 * 365, mean = 15, sd = 5)
df <- data.frame(Year = years, Month = months, Day = days, Values = x)
df_filt = df %>% filter(Year==2010)
df_filt$Distance <- NA
for(i in 3:nrow(df_filt)) {
if (df_filt$Values[i] > df_filt$Values[i-1] && df_filt$Values[i-1] > df_filt$Values[i-2]) {
df_filt$Distance[i] =
(1/3)*(sqrt((df_filt$Values[i] - df_filt$Values[i-2])^2) +
sqrt((df_filt$Values[i] - df_filt$Values[i-1])^2) +
sqrt((df_filt$Values[i-2] - df_filt$Values[i-1])^2))
}
else{
df_filt$Distance[i] <- NA
}
}
</code>
seed(123)
years <- rep(2010:2014, each = 365)
months <- rep(rep(1:12, each = 31), 5)[1:(5 * 365)]
days <- rep(1:31, times = 5 * 12)[1:(5 * 365)]
# Create a data frame with year, month, day,
x <- rnorm(5 * 365, mean = 15, sd = 5)
df <- data.frame(Year = years, Month = months, Day = days, Values = x)
df_filt = df %>% filter(Year==2010)
df_filt$Distance <- NA
for(i in 3:nrow(df_filt)) {
if (df_filt$Values[i] > df_filt$Values[i-1] && df_filt$Values[i-1] > df_filt$Values[i-2]) {
df_filt$Distance[i] =
(1/3)*(sqrt((df_filt$Values[i] - df_filt$Values[i-2])^2) +
sqrt((df_filt$Values[i] - df_filt$Values[i-1])^2) +
sqrt((df_filt$Values[i-2] - df_filt$Values[i-1])^2))
}
else{
df_filt$Distance[i] <- NA
}
}