I'm doing the following in order to import some txt tables and keep them as list:
# set working directory - the folder where all selection tables are stored hypo_selections<-list.files() # change object name according to each species hypo_list<-lapply(hypo_selections,read.table,sep="\t",header=T) # change object name according to each species
I want to access one specific element, let's say hypo_list[1]. Since each element represents a table, how should I procced to access particular cells (rows and columns)?
I would like to do something like it:
a<-hypo_list[1] a[1,2]
But I get the following error message:
Error in a[1, 2] : incorrect number of dimensions
Is there a clever way to do it?
Thanks in advance!
In order to reference a list member directly, we have to use the double square bracket "[[]]" operator. The following object x[[2]] is the second member of x. In other words, x[[2]] is a copy of s, but is not a slice containing s or its copy. We can modify its content directly.
To find the (row, column) index pair of an element in a list of lists, iterate over the rows and their indices using the enumerate() function and use the row. index(x) method to determine the index of element x in the row .
The list() function is used to create lists in R programming. We can use the [[index]] function to select an element in a list. The value inside the double square bracket represents the position of the item in a list we want to extract.
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 list l[[1]] # returns anscombe dataframe anscombe[1:2, 2] # access first two rows and second column of dataset [1] 10 8 l[[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 list tbl1[1:2] # access first two elements of table 1
Now with the list
l[[1]] # access first table from the list 1 2 3 4 5 9 11 12 9 9 l[[1]][1:2] # access first two elements in first table 1 2 9 11
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With