8

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.

zx8754
  • 52,746
  • 12
  • 114
  • 209
paploo
  • 153
  • 1
  • 2
  • 5
  • What is your data structure? And what have you tried so far? – dayne Dec 14 '17 at 20:09
  • Hi dayne, it is a data frame and I have tried the below: df[1,1] / df[1,6] for 2/20 , df[1,2] / df[1,6] for 3/20 and so on as I need to get assign a value to each calculation. do you know if there is a faster way? – paploo Dec 14 '17 at 22:31
  • 2
    You should spend some time reading this: https://stackoverflow.com/help/how-to-ask – dayne Dec 14 '17 at 22:32

2 Answers2

18

You can simply do

df[,1:5] / df[,6] 
mtoto
  • 23,919
  • 4
  • 58
  • 71
  • 3
    As a note, the same syntax works whether the data structure is a matrix or data.frame. – dayne Dec 14 '17 at 20:23
  • 1
    I somehow get this error : `Error in Ops.data.frame(df[, 2:13], df[, 14]) : ‘/’ only defined for equally-sized data frames` . Any suggestions why that would happen? – Tom Jan 29 '21 at 18:12
  • 3
    I will leave my comment above for the next idiot. With respect to my own comment: you need to convert to `data.frame`. – Tom Jan 29 '21 at 18:14
7

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
ToWii
  • 590
  • 5
  • 8