# How to divide data frame row values by maximum value in each row excluding 0 in R?

To divide data frame row values by row maximum excluding 0 in R, we can follow the below steps −

• First of all, create a data frame.
• Then, use apply function and if else function to divide the data frame row values by row maximum excluding 0.

## Create the data frame

Let's create a data frame as shown below −

Live Demo

x<-sample(0:2,25,replace=TRUE)
y<-sample(0:2,25,replace=TRUE)
z<-sample(0:2,25,replace=TRUE)
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 0 1
2 1 0 0
3 0 0 0
4 1 0 1
5 0 0 2
6 2 0 1
7 1 2 0
8 2 0 2
9 0 2 1
10 0 2 0
11 1 2 0
12 2 2 1
13 0 0 1
14 1 1 0
15 2 1 2
16 2 0 2
17 2 1 0
18 0 0 0
19 0 0 0
20 1 2 2
21 2 0 1
22 2 0 2
23 2 1 2
24 0 2 1
25 0 2 2

## Divide the data frame row values by row maximum excluding 0

Using apply function to divide the row values of df by row maximum excluding 0 −

Live Demo

x<-sample(0:2,25,replace=TRUE)
y<-sample(0:2,25,replace=TRUE)
z<-sample(0:2,25,replace=TRUE)
df<-data.frame(x,y,z)
df_new<-t(apply(df,1, function(x) if (0 %in% x) x else x/max(x)))
df_new

### Output

      x   y    z
[1,] 0.0 0.0 1.0
[2,] 1.0 0.0 0.0
[3,] 0.0 0.0 0.0
[4,] 1.0 0.0 1.0
[5,] 0.0 0.0 2.0
[6,] 2.0 0.0 1.0
[7,] 1.0 2.0 0.0
[8,] 2.0 0.0 2.0
[9,] 0.0 2.0 1.0
[10,] 0.0 2.0 0.0
[11,] 1.0 2.0 0.0
[12,] 1.0 1.0 0.5
[13,] 0.0 0.0 1.0
[14,] 1.0 1.0 0.0
[15,] 1.0 0.5 1.0
[16,] 2.0 0.0 2.0
[17,] 2.0 1.0 0.0
[18,] 0.0 0.0 0.0
[19,] 0.0 0.0 0.0
[20,] 0.5 1.0 1.0
[21,] 2.0 0.0 1.0
[22,] 2.0 0.0 2.0
[23,] 1.0 0.5 1.0
[24,] 0.0 2.0 1.0
[25,] 0.0 2.0 2.0

Updated on: 14-Aug-2021

273 Views