Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is using aggregate function in R vs sum(Dataframe$columns)/N different?

I have a dataframe X that looks like this:

A B C D E Identifier  
1 2 3 4 5          a  
2 3 2 2 1          b  
4 5 4 5 3          a   
2 3 4 5 6          a  
0 0 1 2 3          a  
1 2 1 1 1          b  

(here the range is 6 as the period over which observations are recorded is 6.)

Now I want to calculate averages for each of A, B, C, D,E based on Identifier. To do that I used Process1

avgcalls <- function(calls){
  totcalls <- sum(calls)
  out <- totcalls/6
  return(out)
}

avgcallsdf <- data.frame((aggregate(X[, 1:4], by = X[6], avgcalls)))

The output looks like this

  Identifier        A          B    C     D
1          a  1.66667  1.6666667  2.0   2.5 
2          b  0.50000  0.8333333  0.5   0.5

Alternatively I did(please suggest a better way to do this)
Process2

samp1<-D[which(D$Identifier=='a')] #creating one dataframe with identifier as 'a'  
samp2<-D[which(D$Identifier=='b')]#creating another dataframe with'b'as identifier  

#calculating means   
mean1<-sum(sampl$A, na.rm=TRUE)/6  
mean2<-sum(sampl$B, na.rm=TRUE)/6  
mean3<-sum(sampl$C, na.rm=TRUE)/6  
mean4<-sum(sampl$D, na.rm=TRUE)/6
mean5<-sum(samp1$E, na.rm=TRUE)/6
finaldf<-data.frame(mean1,mean2,mean3,mean4,mean5)

similarly I do above with samp2 Both results are identical.

My actual data has 1008 columns and around 80,000 rows, will the results vary from Process 1 and Process2 if there are NA's present?

I looked at this Getting different results using aggregate() and sum() functions in R but it wasn't very helpful

like image 230
kRazzy R Avatar asked Jul 25 '26 21:07

kRazzy R


1 Answers

We can also use data.table

library(data.table)
setDT(df1)[, lapply(.SD, mean), Identifier]
#   Identifier    A   B   C   D    E
#1:          a 1.75 2.5 3.0 4.0 4.25
#2:          b 1.50 2.5 1.5 1.5 1.00

If we need the sum divided by n=6

setDT(df1)[, lapply(.SD, function(x) sum(x, na.rm=TRUE)/6), Identifier] 
#   Identifier        A         B   C        D         E
#1:          a 1.166667 1.6666667 2.0 2.666667 2.8333333
#2:          b 0.500000 0.8333333 0.5 0.500000 0.3333333
like image 145
akrun Avatar answered Jul 27 '26 13:07

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!