How to extract data frame columns stored in a list in R?


Suppose we have two frames each having 5 columns that are stored in a list in R and the data that belongs to same columns has some kind of inherent relationship or we want to check whether there exists a relationship between them then we might want to extract those columns. Therefore, we can use lapply function for this extraction. For example, if we have a list called LIST that store two data frames then column 3 of each data frame can be extracted by using the command lapply(LIST,"[",3).

Example

Consider the below data frames and list of these data frames −

 Live Demo

df1<-data.frame(x1=rnorm(20),x2=rnorm(20))
df2<-data.frame(y1=rnorm(20),y2=rnorm(20))
List<-list(df1,df2)
List

Output

[[1]]
    x1            x2
1  -0.2616691   0.4838822161
2  -0.4962192  -0.2029131423
3  -0.6289051   0.6067368122
4  -1.8650979  -0.2673970799
5  -0.1144585   1.2794435497
6  -0.7950920   0.3237400683
7  -0.7473936   0.5272240477
8  -1.1275262   0.8650962534
9  -0.2354747   1.0057184299
10  1.3755067   0.0961681148
11 -0.1747653   1.2535584458
12 -1.5245065   1.0977974301
13 -1.9052953  -0.6178104611
14  0.6634748   0.3078744775
15 -0.3464213  -0.9288219551
16 -1.7638077  -1.3873331806
17 -0.6839449  -0.0006287789
18 -0.1494119   0.1155562131
19 -0.3583126   0.2606700288
20 -0.6148202  -0.5952164804
[[2]]
      y1            y2
1   -0.211831075   0.80770142
2   0.275355837  -0.37532157
3   0.026130608   0.07003241
4  -0.214784788   0.36447807
5  -0.706518246  -2.35280957
6  -0.786380214  -0.83800239
7   0.599793658   1.00900869
8  -0.952037717   0.31360048
9  -0.820999108   1.37718684
10 -1.912105297  -0.48305776
11  0.436298130   0.56800539
12  1.126854489   0.26761877
13 -2.148552234  -1.54496557
14  1.832004140  -0.93939487
15 -0.587988585   0.74063570
16  0.945827064  -0.30905531
17 -1.571678758  -0.44346002
18 -0.704557448  -0.78744069
19 -0.009306419   0.71375917
20  0.734797879  -1.88248741

Extracting column 2 from each data frame stored in List −

Example

lapply(List,"[",2)

Output

[[1]]
       x2
1   0.4838822161
2  -0.2029131423
3   0.6067368122
4  -0.2673970799
5   1.2794435497
6   0.3237400683
7   0.5272240477
8   0.8650962534
9   1.0057184299
10  0.0961681148
11  1.2535584458
12  1.0977974301
13 -0.6178104611
14  0.3078744775
15 -0.9288219551
16 -1.3873331806
17 -0.0006287789
18  0.1155562131
19  0.2606700288
20 -0.5952164804
[[2]]
     y2
1   0.80770142
2  -0.37532157
3   0.07003241
4   0.36447807
5  -2.35280957
6  -0.83800239
7   1.00900869
8   0.31360048
9   1.37718684
10 -0.48305776
11  0.56800539
12  0.26761877
13 -1.54496557
14 -0.93939487
15  0.74063570
16 -0.30905531
17 -0.44346002
18 -0.78744069
19  0.71375917
20 -1.88248741

Updated on: 16-Mar-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements