r - 何时使用 select_at、mutate_at 等函数?
问题描述
我一直在玩弄verb_at
, verb_if
,verb_each
函数dplyr
。
我发现的示例仅显示了verb_if
和的用例verb_all
。
有人可以为其余功能提供一些用例。
解决方案
看看?select_vars
和?select_helpers
从dplyr
帮助。函数的目的verb_at
是使用select_helpers
函数根据变量名称或索引选择变量并将函数应用于该变量。一些例子:
data(iris)
# Convert all columns containing Sepal data to integers
x <- mutate_at(iris, vars(contains("Sepal")), as.integer)
head(x)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5 3 1.4 0.2 setosa
2 4 3 1.4 0.2 setosa
3 4 3 1.3 0.2 setosa
4 4 3 1.5 0.2 setosa
5 5 3 1.4 0.2 setosa
6 5 3 1.7 0.4 setosa
# Summarize the mean of all variables containing "Sepal"
summarise_at(iris, vars(contains('Sepal')), mean)
Sepal.Length Sepal.Width
1 5.843333 3.057333
select_at
通常不需要,因为select
已经限定并接受select_helpers
. 正如这个答案所说,使用的一个优点select_at
是它允许您应用一个函数来重命名选定的变量:
data(starwars)
# Select Variables
select(starwars, ends_with('Color')) %>%
head()
# A tibble: 6 x 3
hair_color skin_color eye_color
<chr> <chr> <chr>
1 blond fair blue
2 NA gold yellow
3 NA white, blue red
4 none white yellow
5 brown light brown
6 brown, grey light blue
# Select and rename variables
select_at(starwars, vars(ends_with('Color')), toupper) %>%
head
# A tibble: 6 x 3
HAIR_COLOR SKIN_COLOR EYE_COLOR
<chr> <chr> <chr>
1 blond fair blue
2 NA gold yellow
3 NA white, blue red
4 none white yellow
5 brown light brown
6 brown, grey light blue
推荐阅读
- python - 在字典 Python 中标记单词
- c++ - 每种类型的可变参数模板的调用权模板特化
- node.js - 使用 NestJS 编写 blob 内容的方法是什么?
- django - 如何在没有扩展名的情况下在 django 中获取图像名称
- flutter - Flutter如何让文本字段中的光标停止移动到开头?
- python - 如何解决“'NoneType'对象不可下标”的问题?
- c# - ExecuteNonQuery 无法创建 TempTable SQL Server
- sharepoint - 如何通过单击徽标将一个共享点发送到另一个共享点
- sql - 以下代码的结果只是作为表格的输入数据
- azure - Azure 逻辑应用程序 - 如何从动态数组创建唯一数组?