Mean of every two columns for large dataset

Viewed 42

As shown below I have a large dataset with 12 hourly temperatures organised in columns. I wish to take the daily mean, i.e. average two columns at a time until the end of the dataset. Could somebody point me in the direction of an easy solution? I know this is probably very straightforward but I can't find any existing solution.

01.01.2000 00:00     01.01.2000 12:00     02.01.2000 00:00     02.01.2000 12.00
3.5                  8.9                  3.8                  9.1
2 Answers

Get the indexes of odd and even columns and calculate an average:

odds = seq(1, ncol(your_data), by = 2)
evens = odds + 1
result = (your_data[odds] + your_data[evens]) / 2

We could do this using recycling logical index

out <- (df[c(TRUE, FALSE)] + df[c(FALSE, TRUE)])/2
Related