试图制作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
来删除那些类为 integer
或 numeric
的列
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/