How to divide each value in an R data frame by 100?

R ProgrammingServer Side ProgrammingProgramming

We sometimes need to perform mathematical operations on all values in the data set. One such operation could be dividing each value by 100.

For example, if we have a data frame called df then we can divide each value in df by 100 by using the below command −

df[,1:ncol(df)]/100

Example

Following snippet creates a sample data frame −

x1<-rpois(20,25)
x2<-rpois(20,21)
x3<-rpois(20,37)
x4<-rpois(20,32)
df1<-data.frame(x1,x2,x3,x4)
df1

Output

The following dataframe is created −

   x1  x2  x3  x4
1  34  17  33  42
2  29  22  28  39
3  28  24  35  26
4  17  21  34  26
5  28  15  38  40
6  20  15  37  30
7  24  18  33  35
8  29  25  43  24
9  37  21  37  34
10 15  16  37  28
11 27  26  38  28
12 33  24  42  31
13 21  23  33  30
14 17  19  39  31
15 26  17  46  21
16 22  29  49  32
17 28  24  40  37
18 21  12  38  34
19 22  19  41  33
20 28  10  36  27

Now to divide each value in df1 by 100, add the following code to the above snippet −

df1[,1:ncol(df1)]/100

The following dataframe is created −

    x1     x2    x3    x4
1  0.34  0.17  0.33  0.42
2  0.29  0.22  0.28  0.39
3  0.28  0.24  0.35  0.26
4  0.17  0.21  0.34  0.26
5  0.28  0.15  0.38  0.40
6  0.20  0.15  0.37  0.30
7  0.24  0.18  0.33  0.35
8  0.29  0.25  0.43  0.24
9  0.37  0.21  0.37  0.34
10 0.15  0.16  0.37  0.28
11 0.27  0.26  0.38  0.28
12 0.33  0.24  0.42  0.31
13 0.21  0.23  0.33  0.30
14 0.17  0.19  0.39  0.31
15 0.26  0.17  0.46  0.21
16 0.22  0.29  0.49  0.32
17 0.28  0.24  0.40  0.37
18 0.21  0.12  0.38  0.34
19 0.22  0.19  0.41  0.33
20 0.28  0.10  0.36  0.27

Example

Following snippet creates a sample data frame −

y1<-sample(100:200,20)
y2<-sample(100:200,20)
y3<-sample(100:200,20)
df2<-data.frame(y1,y2,y3)
df2

Output

The following dataframe is created −

    y1   y2   y3
1  154  132  114
2  199  106  190
3  161  196  141
4  127  184  103
5  177  120  183
6  113  194  137
7  128  181  142
8  192  135  164
9  100  139  127
10 175  114  200
11 184  147  172
12 187  164  132
13 162  173  184
14 130  161  102
15 157  102  150
16 134  110  157
17 140  192  139
18 119  195  111
19 150  148  187
20 110  188  146

Now, to divide each value in df2 by 100, add the following code to the above snippet −

df2[,1:ncol(df2)]/100

The following dataframe is created −

    y1    y2    y3
1  1.54  1.32  1.14
2  1.99  1.06  1.90
3  1.61  1.96  1.41
4  1.27  1.84  1.03
5  1.77  1.20  1.83
6  1.13  1.94  1.37
7  1.28  1.81  1.42
8  1.92  1.35  1.64
9  1.00  1.39  1.27
10 1.75  1.14  2.00
11 1.84  1.47  1.72
12 1.87  1.64  1.32
13 1.62  1.73  1.84
14 1.30  1.61  1.02
15 1.57  1.02  1.50
16 1.34  1.10  1.57
17 1.40  1.92  1.39
18 1.19  1.95  1.11
19 1.50  1.48  1.87
20 1.10  1.88  1.46
raja
Updated on 02-Nov-2021 06:06:50

Advertisements