Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有没有一种快速的方法来搜索R中的变量?_R_Stata - Fatal编程技术网

有没有一种快速的方法来搜索R中的变量?

有没有一种快速的方法来搜索R中的变量?,r,stata,R,Stata,在Stata中,lookfor命令提供了一种在数据集中搜索变量的快速方法(它同时搜索变量名称和标签)。因此lookforeducation可以快速找到与教育相关的变量。R中是否有等效的快捷功能?您只需grepdata.frame即可获得必要的信息。然后,您将获得更多的信息,而不仅仅是匹配某个人的变量名称列表。还可以使用正则表达式,从而增强搜索能力。下面是一个函数的示例,该函数可以执行您想要的操作(仅适用于data.frame): 我在会话开始时运行的oneliner怎么样: lkf <-

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

您只需
grep
data.frame即可获得必要的信息。然后,您将获得更多的信息,而不仅仅是匹配某个人的变量名称列表。还可以使用正则表达式,从而增强搜索能力。下面是一个函数的示例,该函数可以执行您想要的操作(仅适用于data.frame):


我在会话开始时运行的oneliner怎么样:

lkf <- function(d,p) names(d)[grep(p,names(d))]
这是一个不需要引用变量名的版本

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)
    }
}

lookfor如果您只需要搜索变量列表以找到您要查找的变量,则可以使用RStudio中的代码完成功能(从v0.99开始)。只要开始输入,你就会得到一个可能匹配的列表。因此,在您的案例中,键入
education$
,并显示数据框中包含的变量列表。滚动浏览这些文件并选择所需文件。

投票迁移到stackoverflow,但如果使用数据帧,则可以将
which()
命令与
names()
命令组合使用,如果使用矩阵,则可以使用
colnames()
lkf <- function(d,p) names(d)[grep(p,names(d))]
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)
    }
}