rTable函数用于列表元素



我有一个列表,看起来像这样:

列表([1])

 GN  SN1  SN2      
  a   0    0      
  b   1    1     
  c   0    0    
  e   2    2     
  f   0    1    
  d   0    0

列表[[2]]

 GN  SN1  SN2      
  e   0    1      
  f   2    0     
  g   1    1    
  h   2    0     
  i   1    0    
  l   3    0

我想应用"表格"函数对列表中的每个元素(因此对于每个列表[[1]],列表[[2]],…)首先按列,然后按行使用例如这样的结构:apply(list, 1, table) (lapply for lists)或apply(list, 2, table),并以相同的方式按行求和,然后按列求和。

可能是这样的…

lapply(List, apply, 1, table) # table by row
lapply(List, apply, 2, table) # table by cols

输出不太好。

一个更好的输出可以是:

list1 <- lapply(List, apply, 1, table) # table by row
list2 <- lapply(List, apply, 2, table) # table by cols
> # for list1
> lapply(list1, unlist) # output is a list
[[1]]
0 a 1 b 0 c 2 e 0 1 f 0 d 
2 1 2 1 2 1 2 1 1 1 1 2 1 
[[2]]
0 1 e 0 2 f 1 g 0 2 h 0 1 i 0 3 l 
1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 

> # for list2
> library(abind)
> # using abind function from abind package
> abind(lapply(list2, unlist), along=0)  # output is an array
     GN.e GN.f GN.g GN.h GN.i GN.l SN1.0 SN1.1 SN1.2 SN1.3 SN2.0 SN2.1
[1,]    1    1    1    1    1    1     4     1     1     3     2     1
[2,]    1    1    1    1    1    1     1     2     2     1     4     2
> # R base solution
> do.call(rbind, lapply(list2, unlist)) # output is an array
     GN.a GN.b GN.c GN.d GN.e GN.f SN1.0 SN1.1 SN1.2 SN2.0 SN2.1 SN2.2
[1,]    1    1    1    1    1    1     4     1     1     3     2     1
[2,]    1    1    1    1    1    1     1     2     2     1     4     2

最新更新