【问题标题】:Is there a fast way to search for variables in R?有没有一种快速的方法来搜索 R 中的变量?
【发布时间】:2012-10-08 12:49:25
【问题描述】:

在 Stata 中,lookfor 命令提供了一种在数据集中搜索变量的快速方法(它同时搜索变量名称和标签)。所以lookfor education 很快就能找到与教育相关的变量。 R中是否有等效的快捷功能?

【问题讨论】:

  • 投票迁移到 stackoverflow 但如果您正在使用数据框,则可以将 which() 命令与 names() 命令组合使用,如果您正在使用 colnames()一个矩阵

标签: r stata


【解决方案1】:

您可以简单地grep data.frame 以获取必要的信息。然后,您将获得更多信息,而不仅仅是匹配某人的变量名称列表。您还可以使用正则表达式,从而增强您的搜索能力。这是执行您想要的功能的示例(仅适用于 data.frame):

lookfor <- 
function (pattern, data, ...) 
{
    l <- lapply(data, function(x, ...) grep(pattern, x, ...))
    res <- rep(FALSE, ncol(data))
    res[grep(pattern, names(data), ...)] <- TRUE
    res <- sapply(l, length) > 0 | res
    names(res) <- names(data)
    names(res)[res]
}

首先我 grep 每一列,然后我 grep 列名。然后我只保留 grep 是否匹配任何内容的信息,并分别为每一列记录。您可以将任何参数传递给grep,而不是...。如果省略它,此函数将进行简单的字符串匹配。

这是一个例子:

> dt<- data.frame(y=1:10,x=letters[1:10],a=rnorm(10))
> lookfor("a",dt) 
[1] "x" "a"

【讨论】:

    【解决方案2】:

    作为我在会话开始时运行的单线器怎么样:

    lkf <- function(d,p) names(d)[grep(p,names(d))]
    

    其中d 是您的data.frame 的名称,p 是模式。

    所以

    d <- data.frame(a=letters[1:10],b=1:10,c=month.name[1:10])
    lkf(d,'c')
    # [1] "c"
    

    这是一个不需要你引用变量名的版本

    lookfor <- function(string_to_find, data){
        # Extract the arguments and force conversion to string
        pars <- as.list(match.call()[-1])
        data.name <- as.character(pars$data)
        var <- as.character(pars$string_to_find)
    
        # Regular expression search through names
        result <- names(data)[grep(var, names(data))]
    
        if(length(result) == 0) {
            warning(paste(var, "not found in", data.name))
            return(NULL)
        }
        else {
            return(result)
        }
    }
    

    【讨论】:

      【解决方案3】:

      如果您只需要搜索变量列表以找到您要查找的变量,则可以使用 RStudio(v0.99 及更高版本)中的代码完成功能。只需开始输入,您将获得可能匹配的列表。因此,在您的情况下,键入education$,将出现数据框中包含的变量列表。滚动浏览这些并选择您想要的。

      【讨论】:

        猜你喜欢
        • 2021-09-13
        • 1970-01-01
        • 1970-01-01
        • 2011-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-09
        • 2014-09-23
        相关资源
        最近更新 更多