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

R ProgrammingServer Side ProgrammingProgramming

To create a column of square 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 square 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=round(rnorm(25),2))
df2<-data.frame(x=round(rnorm(25,5,1),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
1   0.91
2  -0.39
3   0.64
4   0.09
5   0.35
6  -0.46
7   0.12
8  -0.64
9   0.11
10 -1.70
11 -0.47
12  0.37
13  1.65
14  1.00
15 -0.43
16 -0.05
17  0.44
18  0.17
19 -0.63
20  0.07
21 -1.77
22 -0.15
23  1.00
24  0.91
25 -0.91

[[2]]
    x
1  5.14
2  5.37
3  5.27
4  6.72
5  4.17
6  4.74
7  5.64
8  5.72
9  2.84
10 4.48
11 4.05
12 4.25
13 6.20
14 4.05
15 5.58
16 3.84
17 6.73
18 5.89
19 4.75
20 4.82
21 2.56
22 5.90
23 4.46
24 5.44
25 3.85

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

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

df1<-data.frame(x=round(rnorm(25),2))
df2<-data.frame(x=round(rnorm(25,5,1),2))
List<-list(df1,df2)
lapply(List,function(x) {
+ x$Squared<-x$x^2
+ return(x)
+ })

Output

[[1]]
    x    Squared
1   0.38 0.1444
2   0.77 0.5929
3  -0.88 0.7744
4  -0.49 0.2401
5   0.24 0.0576
6  -0.79 0.6241
7  -1.35 1.8225
8   0.13 0.0169
9   0.74 0.5476
10  0.50 0.2500
11 -0.85 0.7225
12 -0.45 0.2025
13  0.33 0.1089
14  0.66 0.4356
15  1.07 1.1449
16  0.26 0.0676
17  1.07 1.1449
18 -1.03 1.0609
19  0.10 0.0100
20  0.21 0.0441
21 -2.41 5.8081
22  1.31 1.7161
23  1.76 3.0976
24 -0.05 0.0025
25 -1.07 1.1449
[[2]]
    x   Squared
1  5.81 33.7561
2  5.48 30.0304
3  5.27 27.7729
4  5.78 33.4084
5  4.63 21.4369
6  5.48 30.0304
7  3.00 9.0000
8  5.22 27.2484
9  4.75 22.5625
10 6.42 41.2164
11 6.25 39.0625
12 4.87 23.7169
13 3.96 15.6816
14 4.42 19.5364
15 3.56 12.6736
16 5.01 25.1001
17 2.76 7.6176
18 3.45 11.9025
19 5.97 35.6409
20 5.00 25.0000
21 4.16 17.3056
22 3.36 11.2896
23 3.59 12.8881
24 4.74 22.4676
25 3.97 15.7609
raja
Published on 09-Nov-2021 07:45:38
Advertisements