Let's say I have such matrix:
Property Group Numb
1 rule panic 13
2 rule calm 70
3 mild panic 21
4 mild calm 59
5 chaos panic 46
6 chaos calm 43
I want to change the third column: each value is to be divided by the sum of numbers in this column with corresponding group.
For example, first row should be like that:
1 rule panic 13/(13+21+46
)
We divide the value by sum of Numbs
for entries with Group = panic
. I know the brute force of doing it, but would you help me with an elegant way of doing it?
Try
library(dplyr)
df1 %>%
group_by(Group) %>%
mutate(Numb = Numb/sum(Numb))
Or
library(data.table)
setDT(df1)[, Numb1:= Numb/sum(Numb) , Group][]
Or using base R
df1$Numb <- with(df1, ave(Numb, Group, FUN=function(x) x/sum(x)))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments