mysteRious
mysteRious

Reputation: 4314

Ordering of group_by, mutate and summarize in R

Data frame df has three columns: x, y, and n. I want to create a new data frame that groups by x, counts the number of observations in y for that group x, and then sums the values for that group in n.

df <- structure(list(x = c(1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 
5, 5), y = c(1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 4, 1, 2, 1, 2, 3), 
n = c(4L, 3L, 2L, 3L, 2L, 4L, 2L, 2L, 3L, 3L, 2L, 5L, 3L, 
3L, 2L, 3L)), class = "data.frame", row.names = c(NA, -16L))

The target data frame looks like this, where a are the 5 groups from original df:

> print(df2, row.names=FALSE)
 a b  c
 1 4 12
 2 3  8
 3 4 10
 4 2  8
 5 3  8

For some reason I'm not combining the group_by or mutate or summarize statements in the pipe in the right order to make this happen. It feels like a simple solution I'm not seeing right now. If anyone could help I would appreciate.

Upvotes: 2

Views: 590

Answers (3)

akrun
akrun

Reputation: 887611

With base R, we can do

do.call(rbind, by(df, df$x, FUN = function(x) 
     data.frame(b = length(x), c = sum(x$n, na.rm = TRUE))))

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 102359

Here is a data.table option

> setDT(df)[, .(b = .N, c = sum(n)), x]
   x b  c
1: 1 4 12
2: 2 3  8
3: 3 4 10
4: 4 2  8
5: 5 3  8

Upvotes: 2

Duck
Duck

Reputation: 39613

Try this:

library(dplyr)
library(tidyr)
#Code
new <- df %>% group_by(x) %>%
  summarise(b=n(),c=sum(n,na.rm=T))

Output:

# A tibble: 5 x 3
      x     b     c
  <dbl> <int> <int>
1     1     4    12
2     2     3     8
3     3     4    10
4     4     2     8
5     5     3     8

Upvotes: 2

Related Questions