pipe with arrange question

Hi all,

Would some explain why the following code returns 2 rows?

d<-data.frame(id=c(1,2,3,4,5,6,7,8,9,10), x=c(1,2,3,4,3,4,5,2,3,2) )
d%>%arrange(d,x)

I know it should be d%>%arrange(x), just trying to understand how pipe/arrange work in this case.
Thnaks.

Hi,

The arrange is just a sorting function for your data frame. If you say arrange(x), it will output the full data frame (two columns), but sorted by values lowest x to highest. If you say arrange(id, x), it will sort first by id, and then by x if there are multiple x values for one id.

Hope this helps
PJ

Thanks, but I don't get it. Probably because I don't get how pipe works exactly (that's what my question is about). I do understand how to sort with pipe (d%>%arrange(x) or d%>%arrange(id,x)). What I don't understand is why d%>%arrange(d,x) returns this 2 row data frame:
id x
1 2
1 2
(Why not an error message?)

Hi,

In my code, it returns all rows, sorted:

library("dplyr")
d <- data.frame(id=c(1,2,3,4,5,6,7,8,9,10), x=c(1,2,3,4,3,4,5,2,3,2) )
d %>% arrange(id, x)

When I run d %>% arrange(d,x) I get the error Error: Argument 1 is of unsupported type data.frame. The pipe takes the left-hand object (the one before the pipe) and places it as the first argument in the right-hand function (the one after the pipe). For example, mtcars %>% arrange(cyl) is equivalent to arrange(mtcars, cyl).

arrange expects a data frame as its first argument and then any number of column names after the data frame. d %>% arrange(d,x) is equivalent to arrange(d, d, x). The second d is where arrange is instead expecting a column name.

More generally, the pipe takes the result of the previous operation and places it as the first argument in the next operation. For example, these are equivalent:

library(tidyverse)

mtcars %>% group_by(cyl) %>% summarise(mean=mean(mpg))

group_by(mtcars, cyl) %>% summarise(mean=mean(mpg))

summarise(group_by(mtcars, cyl), mean=mean(mpg))
1 Like

Thanks Joel. That shed the light. Also, I tried with the latest dplyr package and depndencies and got the error you mentioned (relieved that the world is round again :)). It might be a bug in the older version I have at my workplace.