在 R 中,x[with(x, order(x$CHROM)), ] 和 x[ order(x$CHROM)) , ] 有什么区别

in R, what's the difference between x[with(x, order(x$CHROM)), ] and x[ order(x$CHROM)) , ]

我尝试了这两个命令,它们 return 结果相同,我只想知道这两个 R 命令之间可能存在的区别:

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

一个例子可以是 运行 在线是: https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/with

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

我认为第一个命令应该是:

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

第二个是:

mtcars[order(mtcars$cyl) , ]

两者 return 相同的结果并且是等效的但是,使用 with 的好处是您不必在引用列名称时一次又一次地引用数据框名称.

假设您想按 3 个变量排序。使用 with 你可以这样做:

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

没有with

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

你想使用什么是选择问题,但它们 return 结果相同 :

identical(mtcars[with(mtcars, order(cyl, am, vs)), ],
          mtcars[order(mtcars$cyl, mtcars$am, mtcars$vs) , ])
#[1] TRUE

没有真正的区别。 with 是一种方便的功能。

示例 1

你可以这样做

iris[order(iris$Species), ]

请注意,您必须使用 $ 分隔符来引用 Species 列。使用 with,我们可以改写:

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

从最终用户的角度来看,以上内容与这样做基本相同:

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

不过,我们应该避免使用attach——我在这里展示它只是出于教学目的——因为它通常会导致namespace/scope令人头疼(哪些变量可用 - 例如,如果您有一个名为 Species 的变量并进行了上述 attach() 调用,则会出现命名冲突)。使用 with 可以避免这种情况,同时仍然可以避免在任何地方使用 $

示例 2

你可以这样写:

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

但与:

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

在这些小例子中使用 with 并没有太大的好处。但是,如果您正在执行更复杂的函数调用,其中您不断引用数据框的不同列,with 就派上用场了。