【发布时间】:2012-05-02 15:29:33
【问题描述】:
我偶尔需要根据其中一个变量的值从 data.frame 中提取特定行。 R 具有最大值 (which.max()) 和最小值 (which.min()) 的内置函数,可让我轻松提取这些行。
中位数是否有等价物?还是我最好只写自己的函数?
这是一个示例 data.frame 以及我将如何使用 which.max() 和 which.min():
set.seed(1) # so you can reproduce this example
dat = data.frame(V1 = 1:10, V2 = rnorm(10), V3 = rnorm(10),
V4 = sample(1:20, 10, replace=T))
# To return the first row, which contains the max value in V4
dat[which.max(dat$V4), ]
# To return the seventh row, which contains the min value in V4
dat[which.min(dat$V4), ]
对于这个特定示例,由于存在偶数个观察值,我需要返回两行,在本例中为第 2 行和第 10 行。
更新
这似乎没有内置函数。因此,以reply from Sacha 为起点,我编写了这个函数:
which.median = function(x) {
if (length(x) %% 2 != 0) {
which(x == median(x))
} else if (length(x) %% 2 == 0) {
a = sort(x)[c(length(x)/2, length(x)/2+1)]
c(which(x == a[1]), which(x == a[2]))
}
}
我可以按如下方式使用它:
# make one data.frame with an odd number of rows
dat2 = dat[-10, ]
# Median rows from 'dat' (even number of rows) and 'dat2' (odd number of rows)
dat[which.median(dat$V4), ]
dat2[which.median(dat2$V4), ]
有什么改进的建议吗?
【问题讨论】: