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)