Alternatively, since you use the formula method in your βsolutionβ, why not use it in a real solution?
Use .
to indicate "all other variables".
In addition, using the formula
method, NA
values ββare processed differently. You need to specify na.rm
for the sum
function and na.pass
for aggregate
.
aggregate(. ~ Year, df, sum, na.rm = TRUE, na.action="na.pass") # Year Find Found # 1 1901 584 497 # 2 1902 364 281 # 3 1903 684 259 # 4 1904 339 260 # 5 1905 42 24 # 6 1906 45 150 # 7 1910 83 78
For a change (and for some simple syntax), of course, data.table
:
library(data.table) DT <- data.table(df) DT[, lapply(.SD, sum, na.rm=TRUE), by = Year] # Year Find Found # 1: 1901 584 497 # 2: 1902 364 281 # 3: 1903 684 259 # 4: 1904 339 260 # 5: 1906 45 150 # 6: 1905 42 24 # 7: 1910 83 78
source share