user553480
user553480

Reputation: 331

count total in column based on other columns - R

How do I convert the dataframe?

Before:

set.seed(1)
df <- data.frame( n = rpois(16, 2),
                  year = rep(2011, 16),
                  month = rep(seq(1,4,1), times = rep(4,4)))

After:

df1 <- data.frame( n = c(8,11,4,9),
                  year = rep(2011, 4),
                  month = rep(seq(1,4,1)))

Upvotes: 3

Views: 90

Answers (2)

akrun
akrun

Reputation: 887981

Using base R with aggregate

aggregate(n ~ ., df, sum)
# year month  n
#1 2011     1  8
#2 2011     2 11
#3 2011     3  4
#4 2011     4  9

Upvotes: 2

Greg
Greg

Reputation: 3670

I think that what you want is this, using dplyr:

library(dplyr)
df %>% 
  group_by(year, month) %>% 
  summarise(n = sum(n))
# A tibble: 4 x 3
# Groups:   year [1]
   year month     n
  <dbl> <dbl> <int>
1  2011     1     8
2  2011     2    11
3  2011     3     4
4  2011     4     9

Upvotes: 4

Related Questions