Dplyr: 选择所有数字列

创建于 2014-07-14  ·  4评论  ·  资料来源: tidyverse/dplyr

最好的方法是什么?
下列

iris %>% select(which(sapply(., is.numeric)))

适用于最新版本的magrittr 。 然而,

iris %>% mutate_each(funs(log), which(sapply(., is.numeric)))

即使使用更新的链运算符,也会抛出Error in lapply(X = X, FUN = FUN, ...) : object '.' not found 。 这是预期的行为吗?

一般来说,通过dplyr某些布尔条件过滤列的最佳方法是什么? 是否值得让另一个选择函数(除了starts_withends_with等)直接作用于列而不是列名? 例如

iris %>% select(satisfies(is.numeric))
feature

最有用的评论

purrr包现在为@steromano的原始问题提供了很好的解决方案,至少对于数据帧。

要保留所有数字列:

iris %>% 
  purrr::keep(is.numeric) %>% 
  head(2)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 1          5.1         3.5          1.4         0.2
#> 2          4.9         3.0          1.4         0.2

要使用单个函数更改所有数字列:

iris %>%
  purrr::map_if(is.numeric, log) %>%
  head(2)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1     1.629241    1.252763    0.3364722   -1.609438  setosa
#> 2     1.589235    1.098612    0.3364722   -1.609438  setosa

所有4条评论

对了,刚注意到

iris %>% mutate_each_q(funs(log), which(sapply(., is.numeric)))

确实有效,这是有道理的。

目前没有最好的办法。 我认为跨后端类型实现将相当困难,但也许我可以添加一些通用方法来确定列类型。

purrr包现在为@steromano的原始问题提供了很好的解决方案,至少对于数据帧。

要保留所有数字列:

iris %>% 
  purrr::keep(is.numeric) %>% 
  head(2)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width
#> 1          5.1         3.5          1.4         0.2
#> 2          4.9         3.0          1.4         0.2

要使用单个函数更改所有数字列:

iris %>%
  purrr::map_if(is.numeric, log) %>%
  head(2)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1     1.629241    1.252763    0.3364722   -1.609438  setosa
#> 2     1.589235    1.098612    0.3364722   -1.609438  setosa

好的! select_if() 工作得很好。 谢谢你。

此页面是否有帮助?
0 / 5 - 0 等级