Generate a new dataframe from a function in R

Viewed 101

I'm kinda new to R and I'm trying to make a simple function that would take a sample of n observations from each of the groups in the df:

df <- data.frame(var1=c(rnorm(50,50,10)),b=letters[1:2])

The idea is to get 2 new df with a sample of n observations from eahc group (a or b).

I've tried this:

random_sample_groups <- function(aorb){
  df_out <- df %>%
    filter(group == "aorb") %>%
    sample_n(10)
}

I don't know how to tell R that df_out are dataframes...

Your help will be appreacited, thanks!!

1 Answers

dplyr and the tidyverse in general are built primarily around interactive use, so they use techniques (e.g. "masking") to make it simpler to access columns within a data frame. To use the same functions programmatically can entail some extra work.

Here, we can make the function group by a column we specify using the "embrace" or "curly curly" operator {{ }}, which makes it possible for the function to access that column name as it exists inside the environment of the function, and to replicate the same kind of behavior you would normally expect from dplyr.

Here are two useful articles that explain more of the theory and necessity for this.

https://dplyr.tidyverse.org/articles/programming.html

https://rlang.r-lib.org/reference/topic-data-mask.html

library(dplyr)
random_sample_groups <- function(my_df, n, grouping){
  my_df %>%
    group_by( {{grouping}} ) %>%
    sample_n(n) %>%
    ungroup()
}

set.seed(42)
random_sample_groups(df, 2, b)


# A tibble: 4 × 2
   var1 b    
  <dbl> <chr>
1  45.0 a    
2  43.4 a    
3  52.9 b    
4  48.2 b    
Related