如何索引R中列表对象的元素 [英] How to index an element of a list object in R
问题描述
我正在执行以下操作以导入一些txt表并将它们保存为列表:
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
我想访问一个特定元素,让我们说hypo_list [1]。由于每个元素代表一个表,我应该如何获取访问特定单元格(行和列)?
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)?
我想做类似的事情:
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?
提前致谢!
推荐答案
索引列表已完成使用双括号,即 hypo_list [[1]]
(例如,看看这里: http://www.r-tutor.com/r-introduction/list )。 BTW: read.table
不返回表而是返回数据帧(请参阅中的值部分?read.table
)。因此,您将拥有一个数据框列表,而不是一个表对象列表。表格和数据框架的主要机制相同。
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.
注意:在R中,第一个条目的索引是 1
(不是 0
与其他一些语言一样)。
Note: In R, the index for the first entry is a 1
(not 0
like in some other languages).
数据帧
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
表格对象
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
现在有了清单
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
这篇关于如何索引R中列表对象的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!