感谢分享,Ken。
你可以使用以下方法:
x <- myDataFrame$MyVariableName; x[x > 100 & x < 180]
你的代码可能需要输入更少的内容,但如果你要分享代码,那么代码的通用性会降低。我自己也有一些类似的节省时间的函数,但要谨慎使用它们,因为它们可能会减慢你的代码速度(额外的步骤),并且在与他人共享文件时还需要包含该函数的代码。
比较编写长度,两者几乎相同:
ss(mtcars$hp, 100 < . & . < 180)
x <- mtcars$hp; x[x > 100 & x < 180]
比较1000次重复的时间。
library(rbenchmark)
benchmark(
tyler = x[x > 100 & x < 180],
ken = ss(mtcars$hp, 100 <. & . < 180),
replications=1000)
test replications elapsed relative user.self sys.self user.child sys.child
2 ken 1000 0.56 18.66667 0.36 0.03 NA NA
1 tyler 1000 0.03 1.00000 0.03 0.00 NA NA
所以,我想这取决于您是否需要速度和/或可共享性与方便性相比。如果只是针对您的小数据集,我认为它很有价值。
编辑:新的基准测试
> benchmark(
+ tyler = {x <- mtcars$hp; x[x > 100 & x < 180]},
+ ken = ss(mtcars$hp, 100 <. & . < 180),
+ ken2 = ss2(mtcars$hp, 100 <. & . < 180),
+ joran = with(mtcars,hp[hp>100 & hp< 180 ]),
+ replications=10000)
test replications elapsed relative user.self sys.self user.child sys.child
4 joran 10000 0.83 2.677419 0.69 0.00 NA NA
2 ken 10000 3.79 12.225806 3.45 0.02 NA NA
3 ken2 10000 0.67 2.161290 0.35 0.00 NA NA
1 tyler 10000 0.31 1.000000 0.20 0.00 NA NA
data.frame(.=x)
更改为list(.=x)
,它似乎仍然可以工作,我认为性能会有所提高。 - IRTFMmyDataFrame$MyVariableName
。我可能应该使用myVeryVeryVeryLongVariableName
或其他名称,但如果我现在编辑它,@joran 的答案就没有太多意义了。=) - Ken Williams