R 使用mutate_at和which.max对数据帧的选定列进行操作
我正在尝试使用R 使用mutate_at和which.max对数据帧的选定列进行操作,r,dplyr,tidyverse,R,Dplyr,Tidyverse,我正在尝试使用mutate_at和which.max的组合来操作数据帧,如下所述 #This is basically what I want to achieve df_want <- iris %>% group_by(Species) %>% mutate(Sepal.Length = Sepal.Length[which.max(Petal.Width)], Sepal.Width = Sepa
mutate_at
和which.max
的组合来操作数据帧,如下所述
#This is basically what I want to achieve
df_want <- iris %>% group_by(Species) %>% mutate(Sepal.Length = Sepal.Length[which.max(Petal.Width)],
Sepal.Width = Sepal.Width[which.max(Petal.Width)])
#Here is my attempt at a smarter solution, but it does not work
df_attempt <- iris %>% group_by(Species) %>% mutate_at(c("Sepal.Length", "Sepal.Width"), function(x) x[which.max("Petal.Width")])
#However, this works
df_test <- iris %>% group_by(Species) %>% mutate_at(c("Sepal.Length", "Sepal.Width"), function(x) x + 100)
在仍然使用
mutate\u at
的情况下,我如何解决这个问题?标准dplyr
方法是:
df_want <- iris %>%
group_by(Species) %>%
mutate(Sepal.Length = Sepal.Length[which.max(Petal.Width)],
Sepal.Width = Sepal.Width[which.max(Petal.Width)])
df_attempt <- iris %>%
group_by(Species) %>%
mutate_at(vars(Sepal.Length, Sepal.Width), funs(.[which.max(Petal.Width)]))
df_所需百分比
组别(种类)%>%
变异(萼片长度=萼片长度[哪个最大(花瓣宽度)],
萼片宽度=萼片宽度[which.max(花瓣宽度)])
df_尝试百分比
组别(种类)%>%
变异_at(变异(萼片长度,萼片宽度),funs([which.max(花瓣宽度)])
结果:
# A tibble: 150 x 5
# Groups: Species [3]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <fctr>
1 5 3.5 1.4 0.2 setosa
2 5 3.5 1.4 0.2 setosa
3 5 3.5 1.3 0.2 setosa
4 5 3.5 1.5 0.2 setosa
5 5 3.5 1.4 0.2 setosa
6 5 3.5 1.7 0.4 setosa
7 5 3.5 1.4 0.3 setosa
8 5 3.5 1.5 0.2 setosa
9 5 3.5 1.4 0.2 setosa
10 5 3.5 1.5 0.1 setosa
# ... with 140 more rows
> identical(df_want, df_attempt)
[1] TRUE
#一个tible:150 x 5
#类群:种[3]
萼片。长萼片。宽花瓣。长花瓣。宽种
1 5 3.5 1.4 0.2刚毛
2 5 3.5 1.4 0.2刚毛
3.5.5 1.3 0.2刚毛
4 5 3.5 1.5 0.2刚毛
5 3.5 1.4 0.2刚毛
6 5 3.5 1.7 0.4刚毛
7 5 3.5 1.4 0.3刚毛
8 5 3.5 1.5 0.2刚毛
9 5 3.5 1.4 0.2刚毛
10 5 3.5 1.5 0.1刚毛
# ... 还有140多行
>相同(想要,尝试)
[1] 真的
注意:
# A tibble: 150 x 5
# Groups: Species [3]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<dbl> <dbl> <dbl> <dbl> <fctr>
1 5 3.5 1.4 0.2 setosa
2 5 3.5 1.4 0.2 setosa
3 5 3.5 1.3 0.2 setosa
4 5 3.5 1.5 0.2 setosa
5 5 3.5 1.4 0.2 setosa
6 5 3.5 1.7 0.4 setosa
7 5 3.5 1.4 0.3 setosa
8 5 3.5 1.5 0.2 setosa
9 5 3.5 1.4 0.2 setosa
10 5 3.5 1.5 0.1 setosa
# ... with 140 more rows
> identical(df_want, df_attempt)
[1] TRUE
vars
可以使用NSE引用变量funs
可以使用
引用每一列,这相当于函数(x)x
所需输出为df_所需。