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

Moh*_*ohr 20 indexing r list lapply read.table

我正在执行以下操作以导入一些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
Run Code Online (Sandbox Code Playgroud)

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

我想做类似的事情:

a<-hypo_list[1]

a[1,2]
Run Code Online (Sandbox Code Playgroud)

但是我收到以下错误消息:

Error in a[1, 2] : incorrect number of dimensions
Run Code Online (Sandbox Code Playgroud)

有一个聪明的方法吗?

提前致谢!

Mar*_*ann 33

使用双括号对列表建立索引,即hypo_list[[1]](例如,请查看此处:http://www.r-tutor.com/r-introduction/list).BTW:read.table不返回表而是返回数据帧(参见值部分?read.table).因此,您将拥有一个数据框列表,而不是一个表对象列表.但是,表和数据框的主要机制是相同的.

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

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
Run Code Online (Sandbox Code Playgroud)

表对象

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 
Run Code Online (Sandbox Code Playgroud)

现在有了清单

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 
Run Code Online (Sandbox Code Playgroud)

  • 对于开发人员来说,索引从"1"开始而不是"0"可能并不明显 (9认同)
  • 足够公平 :-D 对于使用继承自“系统”语言(汇编、C 等,直至 Java、Swift)以及 lisp 语言、BASIC 以及几乎所有“通用”编程的编程语言的开发人员而言,这并不明显现有的语言,如 perl、php 等。 专业工具,如 Matlab 和其他原始非技术语言,如 COBOL (!) 以及 FORTRAN、统计语言等,通常从 1 开始索引。 IBM 等的“委员会设计”语言也是如此。 (3认同)
  • @KarlP相反,从0开始计算一些东西并不是自然界:) (2认同)
  • @Karlp 曾说过“对于开发人员”-因此从 1 开始索引就像从后座开车一样。 (2认同)