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

R ProgrammingServer Side ProgrammingProgramming

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

Create a column of exponent in data frames stored in the list

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

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

Output

[[1]]
   x Exponent
1  5 148.413159
2 10 22026.465795
3  1 2.718282
4  9 8103.083928
5  4 54.598150
6  7 1096.633158
7  9 8103.083928
8  9 8103.083928
9  1 2.718282
10 8 2980.957987
11 3 20.085537
12 7 1096.633158
13 3 20.085537
14 3 20.085537
15 4 54.598150
16 8 2980.957987
17 2 7.389056
18 10 22026.465795
19 8 2980.957987
20 5 148.413159
21 8 2980.957987
22 3 20.085537
23 1 2.718282
24 4 54.598150
25 3 20.085537
[[2]]
   x Exponent
1  13 442413.39
2  15 3269017.37
3  11 59874.14
4  15 3269017.37
5  13 442413.39
6  17 24154952.75
7  14 1202604.28
8  12 162754.79
9  19 178482300.96
10 13 442413.39
11 12 162754.79
12 19 178482300.96
13 12 162754.79
14 18 65659969.14
15 11 59874.14
16 17 24154952.75
17 10 22026.47
18 11 59874.14
19 11 59874.14
20 13 442413.39
21 20 485165195.41
22 12 162754.79
23 17 24154952.75
24 18 65659969.14
25 19 178482300.96
raja
Published on 10-Nov-2021 05:50:07
Advertisements