Rico
Rico

Reputation: 2058

Create function - insert quote or set variables in parentheses

I'm trying to create a function which selects a list of variables in a dataframe. The criterion is simple all variables between two selected ones.

My code so far:

var_bw <- function(v1, v2, data) {
  data[ ,which(names(data)==v1):which(names(data)==v2)]
}

However, v1 and v2 need quotes around them. Must be straightforward...

Upvotes: 0

Views: 195

Answers (1)

Andrie
Andrie

Reputation: 179388

Use substitute:

var_bw <- function(v1, v2, data) {
  index <- which(names(data)==substitute(v1)):which(names(data)==substitute(v2)) 
  data[, index]
}

Some examples using iris:

head(var_bw(Sepal.Length, Petal.Length, iris))
  Sepal.Length Sepal.Width Petal.Length
1          5.1         3.5          1.4
2          4.9         3.0          1.4
3          4.7         3.2          1.3
4          4.6         3.1          1.5
5          5.0         3.6          1.4
6          5.4         3.9          1.7

And

head(var_bw(Petal.Length, Species, iris))
  Petal.Length Petal.Width Species
1          1.4         0.2  setosa
2          1.4         0.2  setosa
3          1.3         0.2  setosa
4          1.5         0.2  setosa
5          1.4         0.2  setosa
6          1.7         0.4  setosa

Upvotes: 1

Related Questions