Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide a number of columns by one column?

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.

like image 361
paploo Avatar asked Dec 14 '17 20:12

paploo


People also ask

How do I divide columns by columns?

To divide columns in Excel, just do the following: Divide two cells in the topmost row, for example: =A2/B2. Insert the formula in the first cell (say C2) and double-click the small green square in the lower-right corner of the cell to copy the formula down the column. Done!

How do I divide a whole column by a number in Excel?

Divide a column of numbers by a constant number In this example, the number you want to divide by is 3, contained in cell C2. Type =A2/$C$2 in cell B2. Be sure to include a $ symbol before C and before 2 in the formula. Drag the formula in B2 down to the other cells in column B.

How do I divide one column in Excel?

On the Data tab, in the Data Tools group, click Text to Columns. The Convert Text to Columns Wizard opens. Choose Delimited if it is not already selected, and then click Next. Select the delimiter or delimiters to define the places where you want to split the cell content.


2 Answers

You can simply do

df[,1:5] / df[,6] 
like image 131
mtoto Avatar answered Sep 21 '22 09:09

mtoto


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
like image 41
ToWii Avatar answered Sep 18 '22 09:09

ToWii