NonSleeper
NonSleeper

Reputation: 851

How to make this select function work in R?

I'm trying to create a function to extract certain columns from a data set. I tried this:

extract <- function(x) {
 x <- select(filter(df),c(id,x))
}  

extract(df$var1)

in which id is an identification variable. But there's an error message saying:

Error: c(id, x) must evaluate to column positions or names, not a double vector

How can I fix this?

Upvotes: 0

Views: 390

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388797

I think what you are trying to do is

library(dplyr)

extract <- function(df, x, id_t){
   select(filter(df, id == id_t), x)
}

You can now call this function as

extract(df, 2:5, 20)

This will select columns 2-5 where id value is 20 in df.


Using an example from mtcars

extract <- function(df, x, id){
   select(filter(df, cyl == id), x)
}
extract(mtcars, 2:5, 6)

#  cyl  disp  hp drat
#1   6 160.0 110 3.90
#2   6 160.0 110 3.90
#3   6 258.0 110 3.08
#4   6 225.0 105 2.76
#5   6 167.6 123 3.92
#6   6 167.6 123 3.92
#7   6 145.0 175 3.62

Here it selects columns 2-5 from mtcars dataset where cyl = 6.

Upvotes: 1

Related Questions