How to index an element of a list object in R How to index an element of a list object in R r r

How to index an element of a list object in R


Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in listl[[1]]             # returns anscombe dataframeanscombe[1:2, 2]   # access first two rows and second column of dataset[1] 10  8l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))tbl2 <- table(sample(1:5, 50, rep=T))l <- list(tbl1, tbl2)  # put tables in a listtbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list1  2  3  4  5 9 11 12  9  9 l[[1]][1:2]            # access first two elements in first table1  2 9 11