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

R ProgrammingServer Side ProgrammingProgramming

To find the log2 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 log2 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  high   first   38    86
2  medium second  44   100
3  medium first   33    68
4  high   first   25    24
5  low    first   34    62
6  low    first   43    55
7  low    first   35    42
8  high   second  21    92
9  low    second  27    78
10 medium first   36    66
11 low    first    2    22
12 high   first   42    40
13 high   second  40    46
14 low    first   28    70
15 medium first   23    53
16 medium first   49    58
17 low    first    6    31
18 low    first   18    79
19 medium second  50    10
20 low    first   31    27
21 high   second  10    43
22 low    second   4    23
23 medium second  20    87
24 high   first   12    69
25 high   second  15     9

Find the log2 if some columns are categorical

Using numcolwise function from plyr package to find the log2 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(log2)(df)

Output

    Score    Demand
1  5.247928 6.426265
2  5.459432 6.643856
3  5.044394 6.087463
4  4.643856 4.584963
5  5.087463 5.954196
6  5.426265 5.781360
7  5.129283 5.392317
8  4.392317 6.523562
9  4.754888 6.285402
10 5.169925 6.044394
11 1.000000 4.459432
12 5.392317 5.321928
13 5.321928 5.523562
14 4.807355 6.129283
15 4.523562 5.727920
16 5.614710 5.857981
17 2.584963 4.954196
18 4.169925 6.303781
19 5.643856 3.321928
20 4.954196 4.754888
21 3.321928 5.426265
22 2.000000 4.523562
23 4.321928 6.442943
24 3.584963 6.108524
25 3.906891 3.169925
raja
Published on 10-Nov-2021 07:15:50
Advertisements