1

这个问题是为了加深对 R 函数 Across & Which 的理解。我运行了这段代码并得到了消息。我想了解

a) 好的和坏的做法有什么区别

b) where 函数在一般情况下和在这个用例中是如何工作的

library(tidyverse)
iris %>% mutate(across(is.character,as.factor)) %>% str()


Warning message:
Problem with `mutate()` input `..1`.
i Predicate functions must be wrapped in `where()`.

  # Bad
  data %>% select(is.character)

  # Good
  data %>% select(where(is.character))

i Please update your code.
4

1 回答 1

3

where使用和不使用没有太大区别。它只是显示一个警告以建议更好的语法。基本上where采用谓词函数并将其应用于数据集的每个变量(列)。然后它返回函数返回的每个变量TRUE。以下示例取自以下文档where

iris %>% select(where(is.numeric))
# or an anonymous function
iris %>% select(where(function(x) is.numeric(x)))
# or a purrr style formula as a shortcut for creating a function on the spot
iris %>% select(where(~ is.numeric(.x)))

或者您也可以使用速记有两个条件&&

# The following code selects are numeric variables whose means are greater thatn 3.5
iris %>% select(where(~ is.numeric(.x) && mean(.x) > 3.5))

您可以使用函数select(where(is.character)).cols参数across,然后.fns在所选列的参数中应用函数。有关更多信息,您始终可以参考文档,这是了解有关这些材料的更多信息的最佳来源。

于 2021-05-13T06:25:54.403 回答