How to create a column of natural log in data frames stored in R list?

R ProgrammingServer Side ProgrammingProgramming

To create a column of natural log 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 natural log 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:20,25,replace=TRUE))
df2<-data.frame(x=sample(1:20,25,replace=TRUE))
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   7
2   3
3  20
4  17
5   7
6   4
7  10
8  18
9  17
10 11
11  7
12  9
13  7
14  7
15 10
16 20
17  7
18 15
19  4
20 14
21 13
22 15
23  9
24  9
25 11
[[2]]
    x
1   7
2   4
3   4
4  18
5  13
6  19
7  15
8  11
9  20
10 18
11 19
12 20
13 17
14 12
15  6
16 10
17  4
18 12
19  9
20 11
21 14
22  6
23 20
24 19
25 11

Create a column of natural log in data frames stored in the list

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

df1<-data.frame(x=sample(1:20,25,replace=TRUE))
df2<-data.frame(x=sample(1:20,25,replace=TRUE))
List<-list(df1,df2)
lapply(List,function(x) {
+ x$NaturalLog<-log(x$x)
+ return(x)
+ })

Output

[[1]]
    x NaturalLog
1   7 1.945910
2   3 1.098612
3  20 2.995732
4  17 2.833213
5   7 1.945910
6   4 1.386294
7  10 2.302585
8  18 2.890372
9  17 2.833213
10 11 2.397895
11  7 1.945910
12  9 2.197225
13  7 1.945910
14  7 1.945910
15 10 2.302585
16 20 2.995732
17  7 1.945910
18 15 2.708050
19  4 1.386294
20 14 2.639057
21 13 2.564949
22 15 2.708050
23  9 2.197225
24  9 2.197225
25 11 2.397895
[[2]]
    x NaturalLog
1   7 1.945910
2   4 1.386294
3   4 1.386294
4  18 2.890372
5  13 2.564949
6  19 2.944439
7  15 2.708050
8  11 2.397895
9  20 2.995732
10 18 2.890372
11 19 2.944439
12 20 2.995732
13 17 2.833213
14 12 2.484907
15  6 1.791759
16 10 2.302585
17  4 1.386294
18 12 2.484907
19  9 2.197225
20 11 2.397895
21 14 2.639057
22  6 1.791759
23 20 2.995732
24 19 2.944439
25 11 2.397895
raja
Updated on 09-Nov-2021 07:54:53

Advertisements