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

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

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

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

df1<-data.frame(x=rpois(25,5),y=rpois(25,3))
df2<-data.frame(x=rpois(25,1),y=rpois(25,2))
List<-list(df1,df2)
lapply(List,function(x) {
+ x$Product<-x$x*x\$y
+ return(x)
+ })

Output

[[1]]
x y Product
1   7 2 14
2   5 4 20
3   7 1  7
4   4 4 16
5   2 3  6
6   5 0  0
7   6 2 12
8   4 4 16
9   4 2  8
10  4 6 24
11  2 2  4
12  3 5 15
13 11 2 22
14  4 3 12
15  4 2  8
16  6 3 18
17 10 6 60
18  6 1  6
19  1 2  2
20  6 1  6
21  3 2  6
22  7 5 35
23  8 4 32
24  7 5 35
25  4 2  8
[[2]]
x y Product
1  0 1 0
2  0 3 0
3  2 1 2
4  1 1 1
5  1 1 1
6  1 0 0
7  2 1 2
8  3 1 3
9  1 1 1
10 1 1 1
11 0 3 0
12 1 2 2
13 1 1 1
14 2 4 8
15 1 2 2
16 3 5 15
17 2 3 6
18 1 1 1
19 1 3 3
20 1 3 3
21 0 4 0
22 0 2 0
23 2 3 6
24 2 1 2
25 1 2 2