I have a data.frame
such as this one:
df=data.frame(id=c("A","A","A","B","B","B"), V=c(3,6,8,5,6,4))
I would like to divide each value of V by the sum of V over the same ID and store the result in a new column. I can reach this by using a for
loop:
for (i in 1:nrow(df)) {
df$y[[i]] <- df$V[[i]]/sum(subset(df, id == df$id[[i]])$V)
}
Which gives the expected output:
id V y
1 A 3 0.1764706
2 A 6 0.3529412
3 A 8 0.4705882
4 B 5 0.3333333
5 B 6 0.4000000
6 B 4 0.2666667
I would like to know if there is a more simple/efficient way to do so, using e.g. the apply
family.
Thanks for your help!