1

我有兴趣减少一个非常大的相关矩阵以仅保留具有负关联的单元格和行。我已经使用df%>%filter_all(any_vars(.<0)) This is an example of the subset of I get later 减少了它。如何根据单元格内容选择列,而不必按名称选择:那些具有任何负值(D 和 E)的列?如果可能的话,我偏爱一个 tidyverse 的答案,但我会尽我所能。我想到了某种across()+ if_else(),因为我不介意将所有非负数都变成NA,但我想不通。

ex <- tribble(~A, ~B, ~C, ~D, ~E,
       "L", 0.133, 0.446, -0.0190, NA,
        "M", 0.166, 0.136,  0.0893, 0.0755,
        "N", 0.110, 0.159,  0.0872, -0.186,
        "O", 0.0161, NA, 0.0272, -0.0767,
      "P",  0.147, 0.0864, 0.0417, -0.0629)
4

2 回答 2

1

我们可以使用selectwith where。在短路 ( &&) 中创建两个条件以匹配列类型 asnumeric并且存在any小于 0 的非 NA 值

library(dplyr)
ex %>%
      dplyr::select(where(~ is.numeric(.) && any(.[complete.cases(.)] < 0)))

-输出

# A tibble: 5 x 2
        D       E
    <dbl>   <dbl>
1 -0.019  NA     
2  0.0893  0.0755
3  0.0872 -0.186 
4  0.0272 -0.0767
5  0.0417 -0.0629

如果我们想保留所选列中小于 0 的任何行

library(purrr)
ex %>%
       dplyr::select(where(~ is.numeric(.) && any(.[complete.cases(.)] < 0))) %>%
       filter(if_any(everything(), ~ . < 0))
# A tibble: 4 x 2
        D       E
    <dbl>   <dbl>
1 -0.019  NA     
2  0.0872 -0.186 
3  0.0272 -0.0767
4  0.0417 -0.0629

如果我们也想保留其他列类型

ex %>%
     dplyr::select(c(where(negate(is.numeric)),
         where(~ is.numeric(.) && any(.[complete.cases(.)] < 0)))) %>% 
     filter(if_any(where(is.numeric), ~ . < 0))
# A tibble: 4 x 3
  A           D       E
  <chr>   <dbl>   <dbl>
1 L     -0.019  NA     
2 N      0.0872 -0.186 
3 O      0.0272 -0.0767
4 P      0.0417 -0.0629
于 2021-06-04T22:45:26.583 回答
0

基础 R 选项 -

#Keep only the columns that have at least one negative value
result <- Filter(function(x) is.numeric(x) && any(x < 0, na.rm = TRUE), ex)
#Turn the values greater than 0 to NA
result[result > 0] <- NA
result

#     D       E
#   <dbl>   <dbl>
#1 -0.019 NA     
#2 NA     NA     
#3 NA     -0.186 
#4 NA     -0.0767
#5 NA     -0.0629
于 2021-06-05T04:06:14.747 回答