首页 > 解决方案 > 如何同时按名称或其标准差选择列?

问题描述

解决方案

我选择了@thelatemail 提供的解决方案,因为我试图坚持使用 tidyverse 并因此使用 dplyr——我还是 R 的新手,所以我正在采取婴儿步骤并利用辅助库。感谢大家抽出宝贵时间提供解决方案。

df_new <- df_inh %>%
select(
  isolate,
  Phenotype,
  which(
    sapply( ., function( x ) sd( x ) != 0 )
  )
)

问题

如果列名是“隔离”或“表型”,或者列值的标准偏差不为 0,我正在尝试选择列。

我已经尝试了以下代码。

df_new <- df_inh %>%
# remove isolate and Phenotype column for now, don't want to calculate their standard deviation
select(
  -isolate,
  -Phenotype
) %>%
# remove columns with all 1's or all 0's by calculating column standard deviation
select_if(
  function( col ) return( sd( col ) != 0 )
) %>%
# add back the isolate and Phenotype columns
select(
  isolate,
  Phenotype
)

我也试过这个

df_new <- df_inh %>%
select_if(
  function( col ) {
  if ( col == 'isolate' | col == 'Phenotype' ) {
    return( TRUE )
  }
  else {
    return( sd( col ) != 0 )
  }
}
)

我可以按标准差或按列名选择列,但我不能同时这样做。

标签: rdataframestandard-deviation

解决方案


不确定您是否可以select_if单独执行此操作,但一种方法是将两个select操作组合起来,然后绑定列。用作mtcars样本数据。

library(dplyr)
bind_cols(mtcars %>% select_if(function(x) sum(x) > 1000), 
          mtcars %>% select(mpg, cyl))

#    disp  hp  mpg cyl
#1  160.0 110 21.0   6
#2  160.0 110 21.0   6
#3  108.0  93 22.8   4
#4  258.0 110 21.4   6
#5  360.0 175 18.7   8
#6  225.0 105 18.1   6
#7  360.0 245 14.3   8
#8  146.7  62 24.4   4
#....

但是,如果一列同时满足条件(在select_if和 中被选中select),那么该列将被重复。

我们还可以使用 base R,它提供相同的输出,但避免使用unique.

sel_names <- c("mpg", "cyl")
mtcars[unique(c(sel_names, names(mtcars)[sapply(mtcars, sum) > 1000]))]

因此,对于您的情况,两个版本将是:

bind_cols(df_inh %>% select_if(function(x) sd(x) != 0), 
          df_inh %>% select(isolate, Phenotype))

sel_names <- c("isolate", "Phenotype")
df_inh[unique(c(sel_names, names(df_inh)[sapply(df_inh, sd) != 0]))]

推荐阅读