How to divide data frame rows by number of columns in R?


To divide data frame rows by number of columns in R, we can follow the below steps −

  • First of all, create a data frame.
  • Then, use apply function to divide the data frame rows by number of columns.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x<-rpois(25,1)
y<-rpois(25,2)
z<-rpois(25,2)
df<-data.frame(x,y,z)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

  x y z
1 0 1 4
2 0 4 2
3 1 3 2
4 1 1 3
5 0 4 2
6 0 2 4
7 2 1 1
8 0 4 1
9 0 2 2
10 0 1 1
11 0 2 5
12 3 3 1
13 1 2 2
14 1 3 4
15 1 1 1
16 3 4 3
17 3 1 2
18 2 2 0
19 1 2 3
20 1 1 0
21 0 1 1
22 2 2 0
23 1 2 1
24 0 2 0
25 0 1 1

Divide the data frame rows by number of columns

Using apply function to divide the rows of df by number of columns in df −

 Live Demo

x<-rpois(25,1)
y<-rpois(25,2)
z<-rpois(25,2)
df<-data.frame(x,y,z)
df_new<-t(apply(df,1, function(x) x/length(x)))
df_new
         x          y       z
[1,] 0.0000000 0.3333333 1.3333333
[2,] 0.0000000 1.3333333 0.6666667
[3,] 0.3333333 1.0000000 0.6666667
[4,] 0.3333333 0.3333333 1.0000000
[5,] 0.0000000 1.3333333 0.6666667
[6,] 0.0000000 0.6666667 1.3333333
[7,] 0.6666667 0.3333333 0.3333333
[8,] 0.0000000 1.3333333 0.3333333
[9,] 0.0000000 0.6666667 0.6666667
[10,] 0.0000000 0.3333333 0.3333333
[11,] 0.0000000 0.6666667 1.6666667
[12,] 1.0000000 1.0000000 0.3333333
[13,] 0.3333333 0.6666667 0.6666667
[14,] 0.3333333 1.0000000 1.3333333
[15,] 0.3333333 0.3333333 0.3333333
[16,] 1.0000000 1.3333333 1.0000000
[17,] 1.0000000 0.3333333 0.6666667
[18,] 0.6666667 0.6666667 0.0000000
[19,] 0.3333333 0.6666667 1.0000000
[20,] 0.3333333 0.3333333 0.0000000
[21,] 0.0000000 0.3333333 0.3333333
[22,] 0.6666667 0.6666667 0.0000000
[23,] 0.3333333 0.6666667 0.3333333
[24,] 0.0000000 0.6666667 0.0000000
[25,] 0.0000000 0.3333333 0.3333333

Updated on: 13-Aug-2021

320 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements