Search code examples
rdplyrnse

Creating a function with multiple arguments using dplyr


I am struggling with using dplyrfunctions in own functions. I am closer to understand but still missing full understanding. Here I have df containing type and D10 variables.

df <- data.frame(type = c("KL", "KL", "A", "A", "B", "B", "9999", "-1"), 
                 D10 = rnorm(8, 3, 4))

I want to write a function that in a new column will return M if the type == "KL"; "-1" if the type %in% c(9999, -1) and that will return K for all the other cases. I want the values of 9999, -1, KL to be possible to change when the function is initiated.

My tries i ended with the function that look like this:

klme <- function(dat, met, minusy = c(-1, 9999), Sortnr, type){
  mutate_call <- lazyeval::interp(~ifelse(a %in% met, "M", ifelse(a %in% minusy, "-1", "K")), a = as.name(Sortnr))
  dat %>% mutate_(.dots = setNames(list(mutate_call), type))
}

klme(df, c("KL"), minusy = c(-1, 9999), "Sortnr", "typ")

that return only K in the typ column while I'd like to obtain output like this:

  type        D10 type.1
1   KL -5.3210620      M
2   KL  4.4832414      M
3    A -5.3979886      K
4    A  2.7933964      K
5    B -0.9602293      K
6    B  4.5097305      K
7 9999 -3.9650796     -1
8   -1  5.2700609     -1

Solution

  • I believe you are looking for this, remember that you need to interp all values that are variable (also @wici was right that your call to klme should not have Sortnr since that is not a column in df):

    df <- data.frame(type = c("KL", "KL", "A", "A", "B", "B", "9999", "-1"), 
                     D10 = rnorm(8, 3, 4))
    
    klme <- function(dat, met, minusy = c(-1, 9999), Sortnr, type){
      mutate_call <- lazyeval::interp(~ifelse(a %in% y, "M", 
                                              ifelse(a %in% z, "-1", "K")),
                                      a = as.name(Sortnr),
                                      y = met,
                                      z = minusy)
      dat %>% mutate_(.dots = setNames(list(mutate_call), type))
    }
    
    klme(df, c("KL"), minusy = c('-1', '9999'), "type", "typ")
    
      type        D10 typ
    1   KL  6.4760905   M
    2   KL  7.5196368   M
    3    A  2.2588101   K
    4    A  1.4910878   K
    5    B -0.3357310   K
    6    B  1.9693856   K
    7 9999 -0.3820483  -1
    8   -1  4.5595150  -1