I want to create a new column in a data frame as a average of values from an already existing column. The average should be in iterative order like
How about this?
df <- data.frame(col_a = c(69, 77, 55, 58, 15, 42, 94, 54, 87, 96, 31, 75, 4, 31, 23, 37, 41, 6, 28))
library(dplyr)
# This is almost what you want
mutate(df, col_b = (cumsum(col_a) - lag(cumsum(col_a), n = 10))/10)
#> col_a col_b
#> 1 69 NA
#> 2 77 NA
#> 3 55 NA
#> 4 58 NA
#> 5 15 NA
#> 6 42 NA
#> 7 94 NA
#> 8 54 NA
#> 9 87 NA
#> 10 96 NA
#> 11 31 60.9
#> 12 75 60.7
#> 13 4 55.6
#> 14 31 52.9
#> 15 23 53.7
#> 16 37 53.2
#> 17 41 47.9
#> 18 6 43.1
#> 19 28 37.2
# This should give exactly what you want
mutate(df, col_b = ifelse(is.na(lag(col_a, 10)) & !is.na(lag(col_a, 9)), cummean(col_a), (cumsum(col_a) - lag(cumsum(col_a), n = 10))/10))
#> col_a col_b
#> 1 69 NA
#> 2 77 NA
#> 3 55 NA
#> 4 58 NA
#> 5 15 NA
#> 6 42 NA
#> 7 94 NA
#> 8 54 NA
#> 9 87 NA
#> 10 96 64.7
#> 11 31 60.9
#> 12 75 60.7
#> 13 4 55.6
#> 14 31 52.9
#> 15 23 53.7
#> 16 37 53.2
#> 17 41 47.9
#> 18 6 43.1
#> 19 28 37.2
Created on 2018-11-22 by the reprex package (v0.2.1)
2 Likes
Thank You for this solution:hugs:
1 Like
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.