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

R ProgrammingServer Side ProgrammingProgramming

To find the log 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 log 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    first  32     83
2  medium first  21     97
3  medium first  30     46
4  medium first  25     99
5  medium second 10     63
6  low    second 11      2
7  medium first  17     98
8  low    first   8     81
9  high   second 23     23
10 high   first  16     68
11 high   second 33     60
12 medium second  9     52
13 medium second  6     56
14 medium first  45     40
15 low    second 31     14
16 low    first  26     72
17 high   second 18     77
18 medium first  43     85
19 medium first  34     73
20 medium second 12     64
21 low    second 39     29
22 medium first  36     37
23 low    second 15     33
24 medium second 14     57
25 low    second 37     35

Find the log if some columns are categorical

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

Output

    Score    Demand
1  3.465736 4.4188406
2  3.044522 4.5747110
3  3.401197 3.8286414
4  3.218876 4.5951199
5  2.302585 4.1431347
6  2.397895 0.6931472
7  2.833213 4.5849675
8  2.079442 4.3944492
9  3.135494 3.1354942
10 2.772589 4.2195077
11 3.496508 4.0943446
12 2.197225 3.9512437
13 1.791759 4.0253517
14 3.806662 3.6888795
15 3.433987 2.6390573
16 3.258097 4.2766661
17 2.890372 4.3438054
18 3.761200 4.4426513
19 3.526361 4.2904594
20 2.484907 4.1588831
21 3.663562 3.3672958
22 3.583519 3.6109179
23 2.708050 3.4965076
24 2.639057 4.0430513
25 3.610918 3.5553481
raja
Published on 09-Nov-2021 06:38:37

Advertisements