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

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

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

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

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

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

## Output

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