How to create a column of log with base 10 in data frames stored in R list?

R ProgrammingServer Side ProgrammingProgramming

To create a column of log with base 10 in data frames stored in R list, we can follow the below steps −

  • First of all, create a list of data frames.

  • Then, use lapply function to create a column of log with base 10 in data frames stored in the list.

Example

Create the list of data frames

Using data.frame function to create data frames and list function to create the list of those data frames −

df1<-data.frame(x=sample(1:100,25))
df2<-data.frame(x=sample(1:100,25))
List<-list(df1,df2)
List

Output

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

[[1]]
   x
1  53
2  74
3  55
4  45
5  85
6  57
7  15
8  92
9   4
10 79
11 28
12 17
13 81
14  6
15 10
16 25
17  2
18  8
19 91
20 48
21 37
22 52
23 42
24 16
25 93
[[2]]
   x
1  88
2  75
3  27
4  90
5  81
6  59
7  14
8  45
9  43
10 31
11 38
12 85
13  2
14 79
15 87
16 52
17 96
18 20
19 77
20  7
21 56
22 80
23 32
24 53
25  9

Create a column of log with base 10 in data frames stored in the list

Using lapply function to create a column of log with base 10 in data frames df1 and df2 stored in the list called List as shown below −

df1<-data.frame(x=sample(1:100,25))
df2<-data.frame(x=sample(1:100,25))
List<-list(df1,df2)
lapply(List,function(x) {
+ x$LogBase10<-log10(x$x)
+ return(x)
+ })

Output

[[1]]
    x LogBase10
1  53 1.7242759
2  74 1.8692317
3  55 1.7403627
4  45 1.6532125
5  85 1.9294189
6  57 1.7558749
7  15 1.1760913
8  92 1.9637878
9   4 0.6020600
10 79 1.8976271
11 28 1.4471580
12 17 1.2304489
13 81 1.9084850
14  6 0.7781513
15 10 1.0000000
16 25 1.3979400
17  2 0.3010300
18  8 0.9030900
19 91 1.9590414
20 48 1.6812412
21 37 1.5682017
22 52 1.7160033
23 42 1.6232493
24 16 1.2041200
25 93 1.9684829
[[2]]
    x LogBase10
1  88 1.9444827
2  75 1.8750613
3  27 1.4313638
4  90 1.9542425
5  81 1.9084850
6  59 1.7708520
7  14 1.1461280
8  45 1.6532125
9  43 1.6334685
10 31 1.4913617
11 38 1.5797836
12 85 1.9294189
13  2 0.3010300
14 79 1.8976271
15 87 1.9395193
16 52 1.7160033
17 96 1.9822712
18 20 1.3010300
19 77 1.8864907
20  7 0.8450980
21 56 1.7481880
22 80 1.9030900
23 32 1.5051500
24 53 1.7242759
25  9 0.9542425
raja
Updated on 10-Nov-2021 05:45:07

Advertisements