r - 我该如何正确处理管道?

标签 r magrittr

试图制作magrittr pinping函数更加优雅和可读。但是,我能做的最好的是如下。我该如何改进它?请找到引用代码,并提供建议。 谢谢

DF <- data.frame(a=letters[1:10], b=1L:10L, c=1.01:1.10, d=rep(TRUE,10), e=10L:1L)

cols <- lapply(DF,class) %>% unlist()
cols[which(cols %in% c("integer","numeric"))]

#        b         c         e 
#"integer" "numeric" "integer"
#
# yet, I'd still like to get rid of the variables.  

我在管道方面能做的最好的就是这样。试过 %$% , 但失败了。

(lapply(DF,class) %>% unlist)[
which(lapply(DF,class) %>% unlist() =="integer" |
      lapply(DF,class) %>% unlist() =="numeric")]

我可以做成这样吗?

lapply(DF,class) %>% unlist %$% .[which(. %in% c("integer","numeric"))]
# of course, it doesn't work

最佳答案

我们可以使用 base R 中的 Filter 来删除那些类为 integernumeric 的列

Filter(function(x) !class(x) %in% c("integer", "numeric"), DF)

为了保留那些变量

Filter(function(x) class(x) %in% c("integer", "numeric"), DF)

或者使用%>%,获取map列的class,判断是否为%in% ,'integer' 或 'numeric',取反(! - 只有当我们需要删除那些变量时)和 magrittr::extract 列基于逻辑索引

library(tidyverse)
map_chr(DF, class) %>% 
    `%in%`(c("integer", "numeric")) %>% 
    #`!` %>%  #in case to remove those columns
    extract(DF, .)

或者用discard来删除列

discard(DF, ~class(.x) %in% c("integer", "numeric"))

keep保留列

keep(DF, ~ class(.x) %in% c("integer", "numeric"))

关于r - 我该如何正确处理管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50383991/

相关文章:

r - R中的行条件子集

r - 如何在 Rstudio 中的同一 Rscript 中的函数之间进行分区?

r - 你如何用赋值运算符结束管道?

r - 带有 magrittr tee 运算符的多个 ggplots

c++ - OpenMP 在 Rcpp 代码中为 SEIR 模型生成段错误

r - 如何将泊松回归的系数限制为 R 中的正数?

r - 在 sqldf 中识别 Inf

r - 向自定义管道函数添加列

r - 使用 %>% 管道和点 (.) 表示法

r - 使用先前 magrittr 链的输出作为进一步参数的参数