如何将具有某些值的元素保留在列表中?

时间:2018-08-02 14:29:57

标签: r

 list(structure(c(20, NA, 25, NA, 30, 0.32, 17,61, 
 32,34, 29, 84), .Dim = c(2L, 
 6L), .Dimnames = list(NULL, c("F", "F1", "F2", "F3", 
 "R4", "R5"))), structure(c(NA, NA, NA, NA, NA, 0.32, 60,61, 
  50,34, 55, 84), .Dim = c(2L, 6L), .Dimnames = list(
NULL, c("F", "F1", "F2", "F3", "F4", "F5" ))), structure(c(100, NA, 20, NA, 
 70, NA, 10,61,2,34,90, 84), .Dim = c(2L,6L), .Dimnames = list(NULL, c("F", 
  "F1", "F2", "F3", "F4", "F5"))))

看起来像:

[[1]]
      F F1    F2 F3 R4 R5
[1,] 20 25 30.00 17 32 29
[2,] NA NA  0.32 61 34 84

[[2]]
      F F1   F2 F3 F4 F5
[1,] NA NA   NA 60 50 55
[2,] NA NA 0.32 61 34 84

[[3]]
       F F1 F2 F3 F4 F5
[1,] 100 20 70 10  2 90
[2,]  NA NA NA 61 34 84

如果一个元素第一行的所有值均<50,则删除该元素。

所需的输出:

[[1]]
      F F1   F2 F3 F4 F5
[1,] NA NA   NA 60 50 55
[2,] NA NA 0.32 61 34 84

[[2]]
       F F1 F2 F3 F4 F5
[1,] 100 20 70 10  2 90
[2,]  NA NA NA 61 34 84

1 个答案:

答案 0 :(得分:2)

list.in <- 
  list(structure(c(20, NA, 25, NA, 30, 0.32, 17,61, 
   32,34, 29, 84), .Dim = c(2L, 
   6L), .Dimnames = list(NULL, c("F", "F1", "F2", "F3", 
   "R4", "R5"))), structure(c(NA, NA, NA, NA, NA, 0.32, 60,61, 
    50,34, 55, 84), .Dim = c(2L, 6L), .Dimnames = list(
  NULL, c("F", "F1", "F2", "F3", "F4", "F5" ))), structure(c(100, NA, 20, NA, 
   70, NA, 10,61,2,34,90, 84), .Dim = c(2L,6L), .Dimnames = list(NULL, c("F", 
    "F1", "F2", "F3", "F4", "F5"))))

# sapply to get TRUE if any non-NA in first row are >= 50
keep <- sapply(list.in, function(x) any(x[1,] >= 50, na.rm = T))

list.in[keep]
# [[1]]
#       F F1   F2 F3 F4 F5
# [1,] NA NA   NA 60 50 55
# [2,] NA NA 0.32 61 34 84
# 
# [[2]]
#        F F1 F2 F3 F4 F5
# [1,] 100 20 70 10  2 90
# [2,]  NA NA NA 61 34 84