Assume I have a tibble (in my example here only with four columns). In real I have two hourly time series therefore 2 times 24 columns:
s1.x,...,s24.x, s1.y,...,s24.y
Now I want to sum up column s1.x with s1.y, s2.x with s2.y to s24.x with s24.y.
a <- tibble(s1.x=2:7, s2.x=3:8, s1.y=4:9, s2.y=5:10)
a %>%
mutate(s1.tot=s1.x+s1.y, s2.tot=s2.x+s2.y)
How can I do this in a short (and elegant way) for all 24 hours?
You can use Map
function:
n = 2 # for your data, use n = 24
a[paste0("s", 1:n, ".tot")] = Map(`+`, a[paste0("s", 1:n, ".x")], a[paste0("s", 1:n, ".y")])
# A tibble: 6 × 6
s1.x s2.x s1.y s2.y s1.tot s2.tot
<int> <int> <int> <int> <int> <int>
1 2 3 4 5 6 8
2 3 4 5 6 8 10
3 4 5 6 7 10 12
4 5 6 7 8 12 14
5 6 7 8 9 14 16
6 7 8 9 10 16 18