Home > other >  Count occurences of elements and sum up its value in R
Count occurences of elements and sum up its value in R

Time:10-24

I have a data frame with 2 columns (Company and Amount). There are multiple companies (string) and a value in another column as numeric.

I want to count all the companies sum the amount for each company. So in the end I want to have a new data frame with 3 columns (Company, Occurrences, Total Amount)

enter image description here

I could count all the occurrences and saved it in a new data frame but have no idea how to get the amount.

library(dplyr)
df_companies %>% count(df_companies$Geldgeber) %>% top_n(3, n) %>% arrange(desc(n))

CodePudding user response:

You can use n() to get the count

library(dplyr)

df_companies %>%
  group_by(Geldgeber) %>%
  summarize(ct = n(), total = sum(Betrag))

You will want to consider how to account for missing values in Betrag, if any. For example, you could initially filter(!is.na(Betrag)), or you can use na.rm=T in the call to sum()

  • Related