dataset - How to create a new vector from grouped data in R? -
possible duplicate on so: computing new variable using conditions of existing data frame
i trying create vector (e.g. z) group means. vector have length equal number of rows of original data frame group mean created , each element of vector z correspond group member.
for example,
a mean of group c mean of group c f mean of group f c mean of group c
etc.
any appreciated.
sounds need function ave
try looking at
?ave
e.g. try
ave(insectsprays$count,insectsprays$spray)
(insectsprays comes r, should work stands) or
with(insectsprays, ave(count,spray))
so equivalent data , assign z
here's (try pasting first 2 lines in , examining insp
):
insp <- insectsprays insp$ave <- with(insp, ave(count,spray)) head(insp,15) count spray ave 1 10 14.50000 2 7 14.50000 3 20 14.50000 4 14 14.50000 5 14 14.50000 6 12 14.50000 7 10 14.50000 8 23 14.50000 9 17 14.50000 10 20 14.50000 11 14 14.50000 12 13 14.50000 13 11 b 15.33333 14 17 b 15.33333 15 21 b 15.33333
the function ave
has many other uses because can supply function argument (and instead of calculating means use whatever other function group wish); particularly subtle use of it, see this answer.
Comments
Post a Comment