0

I have a problem!

I want to define a function to select variable of a df like that

select_var <- function(var1, var2)
  {
    require(dplyr)
    select(df=df,var1,var2)
  }

using select_var like select_var(var_name_1,var_name_2)

without "".

I want to my df my variable !

Then I want to add var 3 var 4 but there are OPTIONNALS SETTING you!thank you !

2
  • How is your function meant to be different from what select does? Here is a good read for how to program with dplyr.
    – markus
    Jun 21, 2018 at 10:11
  • Why don't you use standard 1R` subsetting?
    – vaettchen
    Jun 21, 2018 at 10:11

2 Answers 2

2

You can use enquo and !! as in:

select_var <- function(var1, var2)
{
  require(tidyverse)
  var1 <- enquo(var1)
  var2 <- enquo(var2)

  select(mtcars, !!var1, !!var2)
}

select_var(mpg, gear)

#                     mpg gear
#Mazda RX4           21.0    4
#Mazda RX4 Wag       21.0    4
#Datsun 710          22.8    4
#Hornet 4 Drive      21.4    3
#Hornet Sportabout   18.7    3
#Valiant             18.1    3
# ...

Not sure what you mean by optionals, but maybe something like:

select_var <- function(...)
{
  require(tidyverse)
  vars <- quos(...)

  select(mtcars, !!!vars)
}

select_var(mpg)
select_var(mpg, gear)
select_var(mpg, gear, cyl)
0
0

You can select rows from the same or different dataframes by indexing with the which() function. You can use logical operators to do it across variables.

which(df[,var1] == df[,var1] &
      df[,var2] == df[,var2])

The which() function will return an index of rows that meat the functions criteria. If you want it to return rows from your dataframe you can do something like this:

df[
   which(df[,var1] == df[,var1] &
         df[,var2] == df[,var2])
  ,]

This will call the row numbers in df that meet your criteria.

2
  • No this is not the problem !! I want to subset my dataframe !
    – n_t
    Jun 21, 2018 at 10:09
  • Ok. I am not really sure what you mean. Can you edit the question to be more specific?
    – bstrain
    Jun 21, 2018 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.