Stat.Enthus
Stat.Enthus

Reputation: 345

Transmute at and keep original columns with r

Thanks again for allowing me to be a part of the community. I appreciate it immensely and iv'e learned a lot.

I would like to aggregate two colums as means of the rows (by group) and keep the other columns. transmute_at has done a nice job with the mean, but has dropped the other columns.

Plus, I saw this is a sort of deprecated function, any thoughts on how to do it with dplyr 1.0?

This is the code

prod<-iris 

prod_avg <- iris %>% filter(!is.na(Species) | Species != "")  %>% 
  group_by(Species) %>% 
  transmute_at(
    c("Sepal.Length","Sepal.Width"), ~ mean(.x, na.rm=T))

Upvotes: 1

Views: 1070

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

Instead of transmute_at use mutate_at

library(dplyr)

iris %>% 
  filter(!is.na(Species) | Species != "")  %>% 
  #There are no NA or empty values in Species though
  group_by(Species) %>% 
  mutate_at(vars(c("Sepal.Length","Sepal.Width")), ~ mean(.x, na.rm=TRUE))

In dplyr 1.0.0 use across

iris %>% 
  filter(!is.na(Species) | Species != "")  %>% 
  group_by(Species) %>% 
  mutate(across(c(Sepal.Length,Sepal.Width), ~ mean(.x, na.rm=TRUE)))

Upvotes: 6

Related Questions