Add certain rows in a column that satisfy condition in R? -
i using r , want add values within column if rows satisfy condition. if have data frame data
below:
team mp win atl 14 .4 atl 25 .4 atl 14 .4 bos 14 .55 bos 20 .55 bos 9 .55
how store values of mp
atl
(14+25+14 = 53)and bos
(14+20+9=43)?
edit: if want add new variable multiplies win
mp
/sums
(where sums
sum of mp
each team
). atl
variables, want values .4*14/53 , .4*25/53, , bos
want .55*14/43, .55*20/43, .55*9/43
i think produce you're looking for:
edit
in light of akrun's excellent answer, here's more compact solution:
dat$cumsums <- ave(dat$mp, dat$team, fun=sum) dat$newvar <- with(dat, win * (mp/cumsums))
previous solution
cumsums <- by(data = dat$mp, indices = dat$team, fun = sum) cumsums.df <- data.frame(team = names(cumsums), cumsums = as.numeric(cumsums)) dat <- merge(x=dat, y=cumsums.df, = "team") dat$newvar <- with(dat, win * (mp/cumsums))
results
dat team mp win cumsums newvar 1 atl 14 0.40 53 0.1056604 2 atl 25 0.40 53 0.1886792 3 atl 14 0.40 53 0.1056604 4 bos 14 0.55 43 0.1790698 5 bos 20 0.55 43 0.2558140 6 bos 9 0.55 43 0.1151163
data
dat <- read.csv(text="team,mp,win atl,14,.4 atl,25,.4 atl,14,.4 bos,14,.55 bos,20,.55 bos,9,.55")
Comments
Post a Comment