r - Mean per group in a data.frame -
this question has answer here:
i have data.frame
, need calculate mean per group (i.e. per month
, below).
name month rate1 rate2 aira 1 12 23 aira 2 18 73 aira 3 19 45 ben 1 53 19 ben 2 22 87 ben 3 19 45 cat 1 22 87 cat 2 67 43 cat 3 45 32
my desired output below, values rate1
, rate2
group means. please disregard value, have made example.
name rate1 rate2 aira 23.21 12.2 ben 45.23 43.9 cat 33.22 32.2
this type of operation aggregate
designed for:
d <- read.table(text='name month rate1 rate2 aira 1 12 23 aira 2 18 73 aira 3 19 45 ben 1 53 19 ben 2 22 87 ben 3 19 45 cat 1 22 87 cat 2 67 43 cat 3 45 32', header=true) aggregate(d[, 3:4], list(d$name), mean) group.1 rate1 rate2 1 aira 16.33333 47.00000 2 ben 31.33333 50.33333 3 cat 44.66667 54.00000
here aggregate columns 3 , 4 of data.frame d
, grouping d$name
, , applying mean
function.
or, using formula interface:
aggregate(. ~ name, d[-2], mean)
Comments
Post a Comment