Zameer Abbas
Zameer Abbas

Reputation: 23

How to multiply each element of a dataframe by sum of element in each row in R?

I have a data frame as given below:

Name   Place   a    b  c   sum
xyz      mno    1   2  3   6
pqr      jkl    4   6  1   11

I would like a command in R script which would help me divide numerical values in column "a", "b" and "c" by value in corresponding "sum" column

hence, my output would be like:

Name   Place      a        b       c     sum
xyz     mno       1/6      2/6    3/6     6
pqr     jkl       4/11     6/11   1/11   11

Upvotes: 2

Views: 594

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389175

If you want to keep it as a fraction then you can try the fractions function from the MASS package

library(MASS)
fractions(unlist(df[, 3:5])/df[,6])  

# a1   a2   b1   b2   c1   c2 
# 1/6 4/11  1/3 6/11  1/2 1/11 

This however, evaluates 2/6 to 1/3 and so on.

Upvotes: 0

akrun
akrun

Reputation: 887691

We can try

df1[3:5] <- df1[3:5]/df1[6][row(df1[3:5])]

Or just

df1[3:5] <- df1[3:5]/df1[,6]
df1
#   Name Place         a         b          c sum
#1  xyz   mno 0.1666667 0.3333333 0.50000000   6
#2  pqr   jkl 0.3636364 0.5454545 0.09090909  11

Or using dplyr

library(dplyr)
df1 %>% 
    mutate_each(funs(./df1$sum), a:c)

Or we can use data.table

library(data.table)
setDT(df1)
nm1 <- letters[1:3]
for(j in nm1){
 set(df1, i=NULL, j=j, value= df1[[j]]/df1$sum)
}

Upvotes: 2

Related Questions