Reputation: 173
I have the below dataset:
Monday Tuesday Wednesday Friday Saturday Total
2 3 4 5 6 20
3 6 7 5 1 22
I am doing the below:
I need to divide first row: 2/20, 3/20, 4/20, 5/20, 6/20
And on the second row: 3/22, 6/22, 7/22, 5/22, 1/22
.
I can do this by extracting the columns but it is long and tedious, there must be an easier way.
Upvotes: 8
Views: 17934
Reputation: 660
You can use dlyr
to operate rowwise on multiple columns:
library(tidyverse)
library(margrittr)
df <- data.frame(
Monday=c(2,3),
Tuesday=c(3,6),
Wednesday=c(4,7),
Friday=c(5,5),
Saturday=c(6,1),
Total=c(20,22))
df %>%
mutate(
across(c(1:5),
.fns = ~./Total))
This then returns:
Monday Tuesday Wednesday Friday Saturday Total
1 0.1000000 0.1500000 0.2000000 0.2500000 0.30000000 20
2 0.1363636 0.2727273 0.3181818 0.2272727 0.04545455 22
Upvotes: 7