r - 如何同时按名称或其标准差选择列?
问题描述
解决方案
我选择了@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 )
}
}
)
我可以按标准差或按列名选择列,但我不能同时这样做。
解决方案
不确定您是否可以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]))]
推荐阅读
- javascript - javascript:调用基类函数
- tree - Java TreeSet 是如何实现的
- spring - 仅允许对 Spring Security 中的特定角色访问 url 模式
- python - 与 python pandas 的 SQL 连接(sybase 驱动程序)
- javascript - 如何将 javascript 函数的返回值保存在 django 模板变量中?
- c# - 不确定通过引用传递是否有效
- java - 启动多个线程的线程的线程上下文是什么?
- c# - WPF动态改变GridViewColumn CellTemplate c#
- ethereum - 数组作为映射变量的函数参数
- visual-studio-code - VSCode 对 Java 扩展的语言支持自动将 .settings、.project 和 .classpath 添加到目录