How to find the exponent of each value in columns if some columns are categorical in R data frame?

R ProgrammingServer Side ProgrammingProgramming

To find the exponent of each value if some columns are categorical in R data frame, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use numcolwise function from plyr package to find the exponent if some columns are categorical.

Example

Create the data frame

Let’s create a data frame as shown below −

Level<-sample(c("low","medium","high"),25,replace=TRUE)
Group<-sample(c("first","second"),25,replace=TRUE)
Score<-sample(1:50,25)
Demand<-sample(1:100,25)
df<-data.frame(Level,Group,Score,Demand)
df

Output

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

   Level  Group   Score Demand
1  low    second   6    63
2  low    first   15     6
3  low    first   49    75
4  medium second  29    86
5  low    first   44    94
6  high   second   5    27
7  low    second  21     9
8  low    second  30    35
9  low    first   24    61
10 low    second  33    31
11 low    second  25    88
12 high   second  38    55
13 low    second  43    33
14 medium first   12    70
15 low    second   2    62
16 high   second  40    82
17 low    first   13    57
18 low    second  16     3
19 medium first   36    98
20 low    second  50    36
21 high   first   19    54
22 low    first    9    81
23 low    second   1    66
24 medium second  47    24
25 medium second  28    59

Find the exponent if some columns are categorical

Using numcolwise function from plyr package to find the exponent of each value in numerical columns in the data frame df −

Level<-sample(c("low","medium","high"),25,replace=TRUE)
Group<-sample(c("first","second"),25,replace=TRUE)
Score<-sample(1:50,25)
Demand<-sample(1:100,25)
df<-data.frame(Level,Group,Score,Demand)
library(plyr)
numcolwise(exp)(df)

Output

       Score      Demand
1  1.171914e+16 1.112864e+36
2  4.034288e+02 7.200490e+10
3  9.496119e+19 9.253782e+29
4  3.185593e+16 1.171914e+16
5  1.957296e+11 8.223013e+36
6  9.744803e+09 5.184706e+21
7  6.565997e+07 4.424134e+05
8  4.424134e+05 1.957296e+11
9  2.718282e+00 2.581313e+20
10 3.269017e+06 1.041376e+23
11 7.896296e+13 5.459815e+01
12 2.648912e+10 1.506097e+35
13 1.446257e+12 2.353853e+17
14 4.851652e+08 2.904885e+13
15 2.980958e+03 3.269017e+06
16 3.493427e+19 1.739275e+18
17 1.784823e+08 7.016736e+20
18 1.096633e+03 6.076030e+37
19 1.285160e+19 1.338335e+42
20 2.146436e+14 4.851652e+08
21 1.627548e+05 4.923458e+41
22 3.584913e+09 1.811239e+41
23 2.581313e+20 2.688117e+43
24 5.459815e+01 2.202647e+04
25 5.184706e+21 2.293783e+27
raja
Published on 10-Nov-2021 06:20:27

Advertisements