Reputation: 2529
In Stata, if I have these variables: var1
, var2
, var3
, var4
, var5
, and var6
, I can select all of them with the command var*
. Does R have a similar functionality?
Upvotes: 5
Views: 2168
Reputation: 193517
The select
function from the "dplyr" package offers several flexible ways to select variables. For instance, using @Marius's sample data, try the following:
library(dplyr)
df %>% select(starts_with("var")) # At the start
df %>% select(num_range("var", 1:3)) # specifying range
df %>% select(num_range("var", c(1, 3))) # gaps are allowed
Upvotes: 12
Reputation: 60070
You can grep
to do this kind of regexp matching among the column names:
x = c(1, 2, 3)
df = data.frame(var1=x, var2=x, var3=x, other=x)
df[, grep("var*", colnames(df))]
Output:
var1 var2 var3
1 1 1 1
2 2 2 2
3 3 3 3
So, basically just making use of the usual df[rows_to_keep, columns_to_keep]
indexing syntax, and feeding in the results of grep
as the columns_to_keep
.
Upvotes: 7