Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

R, dplyr - combination of group_by() and arrange() does not produce expected result?

when using dplyr function group_by() and immediately afterwards arrange(), I would expect to get an output where data frame is ordered within groups that I stated in group_by(). My reading of documentation is that this combination should produce such a result, however when I tried it this is not what I get, and googling did not indicate that other people ran into the same issue. Am I wrong in expecting this result?

Here is an example, using the R built-in dataset ToothGrowth:

library(dplyr)
ToothGrowth %>%
  group_by(supp) %>%
  arrange(len)

Running this will produce a data frame where the whole data frame is ordered according to len and not within supp factors.

This is the code that produces the desired output:

ToothGrowth %>%
  group_by(supp) %>%
  do( data.frame(with(data=., .[order(len),] )) )
question from:https://stackoverflow.com/questions/24649730/r-dplyr-combination-of-group-by-and-arrange-does-not-produce-expected-res

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you want

ToothGrowth %>%
  arrange(supp,len)

The chaining system just replaces nested commands, so first you are grouping, then ordering that grouped result, which breaks the original ordering.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...