本文介绍了R中向量的subset()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经基于 subset() 编写了以下函数,我觉得它很方便:

I've written the following function based on subset(), which I find handy:

ss <- function (x, subset, ...)
{
    r <- eval(substitute(subset), data.frame(.=x), parent.frame())
    if (!is.logical(r))
        stop("'subset' must be logical")
    x[r & !is.na(r)]
}

所以,我可以写:

ss(myDataFrame$MyVariableName, 500 < . & . < 1500)

代替

myDataFrame$MyVariableName[ 500 < myDataFrame$MyVariableName
                                & myDataFrame$MyVariableName < 1500]

这似乎是其他人可能已经开发出解决方案的东西 - 包括我可能错过的核心 R 中的某些内容.已经有什么了吗?

This seems like something other people might have developed solutions for, though - including something in core R I might have missed. Anything already out there?

推荐答案

我意识到 Ken 提供的解决方案比仅选择范围内的项目更通用(因为它应该适用于任何逻辑表达式),但这确实提醒我 GregSnow 在他的教学演示包中有比较中缀运算符:

I realize that the solution Ken offers is more general than just selecting items within ranges (since it should work on any logical expression) but this did remind me that Greg Snow has comparison infix operators in his Teaching Demos package:

library(TeachingDemos)
x0 <- rnorm(100)
x0[ 0 %<% x0 %<% 1.5 ]

这篇关于R中向量的subset()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 23:39