Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how do I add a max by group? [duplicate]

Tags:

r

I would like to use R to create a new column in my dataset that includes a maximum for each unique group. My data look like this:

group<-c("A","A","A","A","A","B","B","C","C","C")
replicate<-c(1,2,3,4,5,1,2,1,2,3)
x<-data.frame(cbind(group,replicate))

I'd like to create the third column as shown below - the maximum for each group.

group   replicate max.per.group
A       1         5       
A       2         5
A       3         5
A       4         5
A       5         5
B       1         2
B       2         2
C       1         3
C       2         3
C       3         3
like image 647
Luke Avatar asked Dec 04 '22 15:12

Luke


2 Answers

If you redefine x first (the cbind makes both columns factors),

x<-data.frame(group,replicate)

you can use this:

merge(x,aggregate(replicate~group,x,FUN=max),all.x=TRUE,by="group")
   group replicate.x replicate.y
1      A           1           5
2      A           2           5
3      A           3           5
4      A           4           5
5      A           5           5
6      B           1           2
7      B           2           2
8      C           1           3
9      C           2           3
10     C           3           3
like image 107
James Avatar answered Dec 08 '22 16:12

James


Try

# This is how you create your data.frame
group<-c("A","A","A","A","A","B","B","C","C","C")
replicate<-c(1,2,3,4,5,1,2,1,2,3)
x<-data.frame(group,replicate) # here you don't need c()

# Here's my solution    
Max <- tapply(x$replicate, x$group,max)
data.frame(x, max.per.group=rep(Max, table(x$group)))
 group replicate max.per.group
1      A         1             5
2      A         2             5
3      A         3             5
4      A         4             5
5      A         5             5
6      B         1             2
7      B         2             2
8      C         1             3
9      C         2             3
10     C         3             3
like image 43
Jilber Urbina Avatar answered Dec 08 '22 16:12

Jilber Urbina