Max Lim
Max Lim

Reputation: 21

Data frame grouping using Group by or Aggregate in R

I would wish to create the following table via a current data frame that I have. My current data frame is as follows

ID = c(rep("A",3), rep("B",5), rep("C",4))
NRT = c(3,3,4,5,5,3,3,4,3,3,5,5)
df = as.data.frame(cbind(ID,NRT))
ID NRT
A 3
A 3
A 4
B 5
B 5
B 3
B 3
B 4
C 3
C 3
C 5
C 5

I would like to obtain a table as follows which shows the average of NRT for each unique ID

ID NRT(Average)
A 3.33 (average of NRT for A)
B 4 (average of NRT for B)
C 4 (average of NRT for C)

Thanks all for the help in advance :)

Upvotes: 0

Views: 264

Answers (1)

rcst
rcst

Reputation: 185

If you consider using a data.table instead of a data.frame (note that a data.table inherits from data.frame) this is most easily achieved

library(data.table)

ID = c(rep("A",3), rep("B",5), rep("C",4))
NRT = c(3,3,4,5,5,3,3,4,3,3,5,5)
df = as.data.frame(cbind(ID,NRT))

dt <- as.data.table(df)
dt[, list("NRT (Average)" = mean(NRT)), by = ID]
   ID NRT (Average)
1:  A    3.333333
2:  B    4.000000
3:  C    4.000000

If you want the table to be printed exactly as you posted you can do the following

library(data.table)
dt <- data.table(ID = c(rep("A",3), rep("B",5), rep("C",4)), NRT = c(3,3,4,5,5,3,3,4,3,3,5,5))
dt[, "NRT(Average)" := paste0(mean(NRT), " (average for NRT for ", ID, ")"), by = ID]
dt[, .SD[1], by = ID][, c(1, 3)] 
   ID                             NRT(Average)
1:  A 3.33333333333333 (average for NRT for A)
2:  B                4 (average for NRT for B)
3:  C                4 (average for NRT for C)

Upvotes: 1

Related Questions