首页 > 解决方案 > 何时使用 select_at、mutate_at 等函数?

问题描述

我一直在玩弄verb_at, verb_if,verb_each函数dplyr

我发现的示例仅显示了verb_if和的用例verb_all

有人可以为其余功能提供一些用例。

标签: rdplyr

解决方案


看看?select_vars?select_helpersdplyr帮助。函数的目的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 

推荐阅读