How to create a column of raise to the power of another column in data frames stored in R list?


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

Create a column of raise to the power of another column

Using lapply function to create a column of raise to the power of another column 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),y=sample(1:5,25,replace=TRUE))
df2<-data.frame(x=sample(1:2,25,replace=TRUE),y=sample(1:5,25,replace=TRUE))
List<-list(df1,df2)
lapply(List,function(x) {
+ x$PowerCol2<-(x$x)^(x$y)
+ return(x)
+ })

Output

[[1]]
    x y PowerCol2
1   9 4  6561
2   4 4  256
3   4 1    4
4   6 3  216
5   8 4  4096
6   6 3  216
7   4 1    4
8   5 2   25
9   8 5 32768
10 10 2  100
11  2 4   16
12  9 3  729
13  9 4 6561
14  6 2   36
15 10 3 1000
16 10 1   10
17  4 2   16
18  5 5 3125
19  2 1    2
20  3 4   81
21  7 5 16807
22  7 4 2401
23  4 2   16
24  7 4 2401
25  6 2   36
[[2]]
   x y PowerCol2
1  2 5 32
2  1 5  1
3  1 2  1
4  1 1  1
5  1 4  1
6  2 1  2
7  1 2  1
8  1 2  1
9  1 3  1
10 1 5  1
11 1 2  1
12 2 4 16
13 2 4 16
14 1 3  1
15 2 4 16
16 2 3  8
17 1 1  1
18 2 1  2
19 1 2  1
20 1 5  1
21 2 5 32
22 1 3  1
23 1 4  1
24 2 3  8
25 2 1  2

Updated on: 12-Nov-2021

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements