简体   繁体   中英

For loop in Dplyr

I have a code as below. First the code should run based on the dplyr::arrange(desc(sum.total)) then dplyr::arrange(desc(sum.mpg)) then as the outcome I would like to have a dataframe/datatable. Many thanks in advance

head(mtcars)

my.mtcars <- mtcars %>%
  dplyr::group_by(gear)%>%
  dplyr::summarise(
    sum.total = n(),
    sum.mpg = sum(mpg))%>%
  dplyr::arrange(desc(sum.total)) # Run me first
  #dplyr::arrange(desc(sum.mpg))  # Second Dont run the line above but this

Expected Answer

#with dplyr::arrange(desc(sum.total))
gear sum.total sum.mpg

1     3        15    242.
2     4        12    294.
3     5         5    107.
#with dplyr::arrange(desc(sum.mpg))
gear sum.total sum.mpg

1     4        12    294.
2     3        15    242.
3     5         5    107.
my.mtcars <- mtcars %>%
  dplyr::group_by(gear)%>%
  dplyr::summarise(
    sum.total = n(),
    sum.mpg = sum(mpg)
lapply(c('sum.total', 'sum.mpg'), function(var) arrange(my.mtcars, desc(.data[[var]])))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM