Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a fast way to search for variables in R?

Tags:

r

stata

In Stata the lookfor command offers a quick way to search for variables in a dataset (and it searches both the variable names and labels). So lookfor education quickly finds you variables related to education. Is there an equivalent shortcut function in R?

like image 900
Eduard Grebe Avatar asked Oct 08 '12 12:10

Eduard Grebe


People also ask

How do you find variables in R?

You can use ls() to list all variables that are created in the environment. Use ls() to display all variables. pat = " " is used for pattern matching such as ^, $, ., etc. Hope it helps!

How do I select all variables in R?

You can shift-click to select a range of variables, you can hold shift and press the down key to select one or more variables, and so on. And then you can press Paste and the command with extracted variable names is pasted into your script editor.

How do I select specific data in R?

To select a specific column, you can also type in the name of the dataframe, followed by a $ , and then the name of the column you are looking to select. In this example, we will be selecting the payment column of the dataframe. When running this script, R will simplify the result as a vector.

How do I get a list of column names in R?

To find the column names and row names in an R data frame based on a condition, we can use row. names and colnames function. The condition for which we want to find the row names and column names can be defined inside these functions as shown in the below Examples.


1 Answers

You can simply grep the data.frame for the information necessary. Then you'll get much more information than simply the list of names of variables for which somebody is matched. You can also use regular expressions, thus enhancing your search capabilities. Here is the example of a function which does what you want (works with data.frame only):

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

First I grep each column, then I grep the column names. Then I keep only information whether grep matched anything and record it for each column separately. Instead of ... you can pass any arguments to grep. If you omit it, this function will do a simple string matching.

Here is an example:

> dt<- data.frame(y=1:10,x=letters[1:10],a=rnorm(10))
> lookfor("a",dt) 
[1] "x" "a"
like image 153
mpiktas Avatar answered Sep 24 '22 05:09

mpiktas