如何将函数应用于嵌套列表的每一行?

时间:2018-06-21 15:52:16

标签: r

我有这些数据 示例:

    Lis=list(structure(c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, 
 NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), .Dim = c(4L, 
 6L), .Dimnames = list(NULL, c("SE", "SE.1", "SE.2", "SE.3", 
 "SE.4", "SE.5"))), structure(c(1, 0, 
 7, 8, 1, 79, 2, 3, 2, 9, 
 6, 7, 8, 0,75, 2, 4, 6, 84, 
 2, 5, 4, 8, 1), .Dim = c(4L, 
   6L), .Dimnames = list(NULL, c("SE", "SE.1", "SE.2", "SE.3", 
 "SE.4", "SE.5"))), structure(c(NA, NA, NA, NA, 7, 0, 2,2, 7, 5, 2, 4, 3, 68, 
  9, 1, 5, 76, 09, 1), .Dim = c(4L, 5L), .Dimnames = list(NULL, c("SE", 
  "SE.1", "SE.2", "SE.3", "SE.4"))))

我想这样做:

收集每个元素的第一行,并根据需要填充[[3]]:

  [1,] NA   NA   NA   NA   NA   NA
  [1,]  1    1    2    8    4    5
  [1,] NA    7    7    3    5 NA

现在计算每列的平均值:

第一行的最终输出(但是我需要将其应用于列表的所有行):

  [,1] 1    4   4.5  5.5    4.5   5
  [,2]
  [,3]
  [,4]

我找到了这样的东西,但没有帮助:lapply(lis,[,1)

1 个答案:

答案 0 :(得分:2)

我们可以这样操作:在每个list中创建一个序列列,然后使用map_df,转换为单个数据集,按序列列分组,得到所有列的meansummarise_all

library(tidyverse)
Lis %>%
   map_df(~ 
          as_tibble(.x) %>%
          mutate(rn = row_number())) %>%
    group_by(rn) %>% 
    summarise_all(mean, na.rm = TRUE)
# A tibble: 4 x 7
#     rn    SE  SE.1  SE.2  SE.3  SE.4  SE.5
#  <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1     1     1   4     4.5   5.5   4.5     5
#2     2     0  39.5   7    34    41       4
#3     3     7   2     4    42    46.5     8
#4     4     8   2.5   5.5   1.5   1.5     1