list 如何在R中索引列表对象的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21091202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 02:07:48  来源:igfitidea点击:

How to index an element of a list object in R

rlistindexinglapplyread.table

提问by Mohr

I'm doing the following in order to import some txt tables and keep them as list:

我正在执行以下操作以导入一些 txt 表并将它们保留为列表:

# 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)?

我想访问一个特定的元素,比如说hypo_list[1]。由于每个元素代表一个表格,我应该如何访问特定的单元格(行和列)?

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!

提前致谢!

回答by Mark Heckmann

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.tabledoes 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.

索引列表是使用双括号完成的,即hypo_list[[1]](例如,看看这里:http: //www.r-tutor.com/r-introduction/list)。顺便说一句:read.table不返回表而是返回数据帧(请参阅 中的值部分?read.table)。因此,您将拥有一个数据框列表,而不是一个表对象列表。不过,表和数据框的主要机制是相同的。

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

注意:在 R 中,第一个条目的索引是 a 10与其他一些语言不同)。

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