0

I tried the two commands and they return the same results, I just want to know what's the possible difference between the two R commands:

x[with(x, order(x$CHROM)), ]
x[        order(x$CHROM) , ]

An example can be run online is : https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/with

mtcars[with(mtcars, order(mtcars$cyl)), ]
mtcars[             order(mtcars$cyl) , ]
Waldi
  • 39,242
  • 6
  • 30
  • 78
mendel
  • 1
  • 8

2 Answers2

3

I think the first command should be :

mtcars[with(mtcars, order(cyl)), ]

and the second is :

mtcars[order(mtcars$cyl) , ]

Both of them return the same result and are equivalent however, the benefit of using with is that you don't have to refer the dataframe name again and again when referring to column name.

Imagine you want to order by 3 variables. Using with you can do :

mtcars[with(mtcars, order(cyl, am, vs)), ]

and without with :

mtcars[order(mtcars$cyl, mtcars$am, mtcars$vs) , ]

It is matter of choice what you want to use but both of them return the same result :

identical(mtcars[with(mtcars, order(cyl, am, vs)), ],
          mtcars[order(mtcars$cyl, mtcars$am, mtcars$vs) , ])
#[1] TRUE
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

There's no real difference. with is kind of a convenience function.

Example 1

You could do this

iris[order(iris$Species), ]

Note that you have to refer to the Species column by using the $ separator. Using with, we can instead write:

with(iris, iris[order(Species), ])

From an end user perspective, the above is essentially the same as doing this:

attach(iris)
iris[order(Species), ]
detach(iris)

We should avoid using attach though - I'm only showing it here for instructional purposes - because it often leads to headaches with namespace/scope (what variables are available - e. g. if you had a variable named Species and did the above attach() call, there would be a naming conflict). Using with avoids this kind of thing while still allowing you to avoid using $ everywhere.

Example 2

You could write:

plot(iris$Petal.Width, iris$Petal.Length)

But with with:

with(iris, plot(Petal.Width, Petal.Length))

There's no huge gain from using with in these small examples. But if you are doing more complicated function calls where you're constantly referring to different columns of a data frame, with comes in handy.

datalowe
  • 589
  • 2
  • 7