Home > Software design >  How to use multiple variable from tibble in an user-defined function?
How to use multiple variable from tibble in an user-defined function?

Time:11-12

I have created a tibble consisting of 6 columns containing 6 different variables that will be input for a user defined function. I am new to r, and I don't know how to connect the tibble with user defined function. Please help.

I have replaced the complex user defined function with simple user_defined_function for the sake of discussion. `

library(tidyr)
library(dplyr)
rgb_val <- seq(from=0, to=255, by=10)
rgb_grid <- expand_grid(r1 = rgb_val, g1 = rgb_val, b1 = rgb_val,
                        r2 = rgb_val, g2 = rgb_val, b3 = rgb_val)

user_defined_function <- function(x) {
  x[,1]   x[,2]   x[,3]   x[,4]   x[,5]   x[,6]
}

rgb_grid %>% mutate(new_cols = user_defined_function ())

I want the results of the user_defined_function to be added as new column to the tibble rgb_grid. However, if what I have tried, unsuprisingly, throws an error.

CodePudding user response:

Given you are passing the whole dataframe to the function, you can't use mutate. Rather, just pass the whole dataframe to the function and add that to your data.frame.

(by the way I changed your rgb_val sequence to to = 20 otherwise the dataframe is huge -- are you trying to destroy my computer haha).

Here's an approach with the tidyverse:

rgb_grid %>% 
  bind_cols(setNames(user_defined_function(.), "new_col"))

# A tibble: 729 × 7
      r1    g1    b1    r2    g2    b3 new_col
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>   <dbl>
 1     0     0     0     0     0     0       0
 2     0     0     0     0     0    10      10
 3     0     0     0     0     0    20      20
 4     0     0     0     0    10     0      10
 5     0     0     0     0    10    10      20
 6     0     0     0     0    10    20      30
 7     0     0     0     0    20     0      20
 8     0     0     0     0    20    10      30
 9     0     0     0     0    20    20      40
10     0     0     0    10     0     0      10
# … with 719 more rows

Or with Base R

new_col <- user_defined_function(rgb_grid) 
cbind(rgb_grid, new_col)

CodePudding user response:

You can use the function exactly how you have constructed it as follows:

rgb_grid %>% mutate(new_cols = user_defined_function(rgb_grid)[,1])

Note that because your function takes in a dataframe and returns a one-column dataframe, I've used [,1] to select that one column as a vector. A more typical pattern however, for your user-defined function would be to have multiple parameters, say one for each column that will be used in the function.

  • Related