从R循环到列表对象的子集(从excel表中提取多个表)

时间:2017-06-14 12:02:15

标签: r excel list loops subset

我需要从每个Excel工作表中提取单独的表,并将它们作为列表对象。我有两个列表:" allsheets"包含38张纸,每张纸包括至少2张表,以及" dataRowMeta"包含有关每个表的相关行的信息。例如,

 a1 <- data.frame(y1=c(1:15),y2=c(6:20))
 a2 <- data.frame(y1=c(3:18),y2=c(2:17))
 allsheets <- list(a1, a2)
 d1<- data.frame(starthead=c(1,9),endhead=c(2,10),startdata =c(3,11),
             enddata = c(7,14),footer = c(8,15))
 d2<- data.frame(starthead=c(1,10),endhead=c(2,11),startdata =c(3,12),
             enddata = c(8,15),footer = c(9,16))
 dataRowMeta <- list(d1,d2)


 [[1]]
 y1 y2
 1   1  6
 2   2  7
 3   3  8
 4   4  9
 5   5 10
 6   6 11
 7   7 12
 8   8 13
 9   9 14
 10 10 15
 11 11 16
 12 12 17
 13 13 18
 14 14 19
 15 15 20

 [[2]]
 y1 y2
 1   3  2
 2   4  3
 3   5  4
 4   6  5
 5   7  6
 6   8  7
 7   9  8
 8  10  9
 9  11 10
 10 12 11
 11 13 12
 12 14 13
 13 15 14
 14 16 15
 15 17 16
 16 18 17

这里是dataRowMeta:

 [[1]]
 starthead endhead startdata enddata footer
 1         1       2         3       7      8
 2         9      10        11      14     15

[[2]]
starthead endhead startdata enddata footer
1         1       2         3       8      9
2        10      11        12      15     16

我试图编写一个循环函数,根据dataRowMeta对每个工作表进行子集化,但未能获得所需的输出。 我收到了一个错误      Error in sheet[[a[m]:b[m], ]] : incorrect number of subscripts

我想这是因为我正在迭代列表,而不是矩阵......但是在这种情况下如何告诉R到子集列表?

所以我需要第一和第四列dataRowMeta(starthead和enddata)作为&#34; start&#34;和&#34;结束&#34; id未来表格的行。

tables <- function(allsheets,dataRowMeta){
for(i in 1 : length(dataRowMeta)){
  for (j in 1 : nrow(dataRowMeta[[i]])){
      a <-""
      b <- ""
    a <- dataRowMeta[[i]][j:j,1]
    b <-  dataRowMeta[[i]][j:j,4]
    for (k in 1 : length(allsheets)){
      sheet <- allsheets[k]
      for ( m in 1 : length(a)){
        tbl <-  sheet[[a[m]:b[m],]]
      }
      }
    }
  }}

所需的输出:我对第一个列表的第一个元素(sheet1)有这个:

 sheet1 <- allsheets[[1]]
 tmp1 <- sheet1[dataRowMeta[[1]][1:1,1] :dataRowMeta[[1]][1:1,4] ,] 

 > tmp1
 y1 y2
 1  1  6
 2  2  7
 3  3  8
 4  4  9
 5  5 10
 6  6 11
 7  7 12

并且需要一个可以为所有工作表执行此操作的循环。请帮我弄清楚如何获得它。谢谢!

0 个答案:

没有答案