Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate data in one column based on values in another column

I know there is an easy way to do this...but, I can't figure it out.

I have a dataframe in my R script that looks something like this:

A      B    C
1.2    4    8
2.3    4    9
2.3    6    0
1.2    3    3
3.4    2    1 
1.2    5    1

Note that A, B, and C are column names. And I'm trying to get variables like this:

sum1 <- [the sum of all B values such that A is 1.2]
num1 <- [the number of times A is 1.2]

Any easy way to do this? I basically want to end up with a data frame that looks like this:

    A     num     totalB
   1.2    3       12
   etc    etc     etc

Where "num" is the number of times that particular A value appeared, and "totalB" is the sum of the B values given the A value.

like image 977
CodeGuy Avatar asked Sep 26 '11 20:09

CodeGuy


2 Answers

In dplyr:

library(tidyverse)
A <- c(1.2, 2.3, 2.3, 1.2, 3.4, 1.2)
B <- c(4, 4, 6, 3, 2, 5)
C <- c(8, 9, 0, 3, 1, 1)

df <- data_frame(A, B, C)

df %>%
    group_by(A) %>% 
    summarise(num = n(),
              totalB = sum(B))
like image 86
leerssej Avatar answered Oct 12 '22 09:10

leerssej


I'd use aggregate to get the two aggregates and then merge them into a single data frame:

> df
    A B C
1 1.2 4 8
2 2.3 4 9
3 2.3 6 0
4 1.2 3 3
5 3.4 2 1
6 1.2 5 1

> num <- aggregate(B~A,df,length)
> names(num)[2] <- 'num'

> totalB <- aggregate(B~A,df,sum)
> names(totalB)[2] <- 'totalB'

> merge(num,totalB)
    A num totalB
1 1.2   3     12
2 2.3   2     10
3 3.4   1      2
like image 40
NPE Avatar answered Oct 12 '22 08:10

NPE