Define
df<-read.table(textConnection('egg 1 20 a
egg 2 30 a
jap 3 50 b
jap 1 60 b'))
s.t.
> df
V1 V2 V3 V4
1 egg 1 20 a
2 egg 2 30 a
3 jap 3 50 b
4 jap 1 60 b
My data has no factors so I convert factors to characters:
> df$V1 <- as.character(df$V1)
> df$V4 <- as.character(df$V4)
I would like to "collapse" the data frame by V1 keeping:
- The max of V2
- The mean of V3
- The mode of V4 (this value does not actually change within V1 groups, so first, last, etc might do also.)
Please note this is a general question, e.g. my dataset is much larger and I may want to use different functions (e.g. last, first, min, max, variance, st. dev., etc for different variables) when collapsing. Hence the functions argument could be quite long.
In this case I would want output of the form:
> df.collapse
V1 V2 V3 V4
1 egg 2 25 a
2 jap 3 55 b
I would suggest using
ddply
fromplyr
:You can replace the functions with any calculation you wish. Your V3 column is non-numeric so might want to convert that to a numeric and then compute the mode. For now I am just returning the V3 value of the first row for each of the splits. Or if you don't want to use
plyr
:plyr package will help you:
As R does not have mode function (probably), I put other function. But it is easy to implement a mode function.