Macaronnos
Macaronnos

Reputation: 647

How to change column in matrix according to another column

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?

Upvotes: 3

Views: 65

Answers (2)

Mamoun Benghezal
Mamoun Benghezal

Reputation: 5314

You can also try this

df <- read.table(header=T, text="
 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")
df$Numb/ave(df$Numb, df$Group, FUN="sum")
# [1] 0.1625000 0.4069767 0.2625000 0.3430233 0.5750000 0.2500000

Upvotes: 3

akrun
akrun

Reputation: 887148

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)))

Upvotes: 4

Related Questions