I try to group the rows of a data.frame by the ID column and sum up all the numerical columns and drop the string column. For that, I created a small data.frame df1:
ID string 2018 2019 2020 2021
1: a1 x2 3 3 0 4
2: a2 g3 5 5 4 0
3: a2 n2 11 6 13 3
4: a1 m3 3 21 9 8
5: a2 2w 9 1 16 5
6: a1 ps2 22 4 7 4
7: a1 kg2 6 0 9 6
and I try to get the sum of the years like in df2:
ID 2018 2019 2020 2021
1: a1 34 28 25 22
2: a2 25 12 33 8
I was trying it with the group_by and summarize function of dplyr, but I wasn't able to get what I want.
library(dplyr)
df1 %>%
group_by(ID) %>%
summarize(df$2018 = sum(2018))
Thanks a lot