logo
Tags down

shadow

Purrr and Rlang - mapping functions with quasiquotation


By : CWick
Date : September 17 2020, 08:00 AM
wish of those help If I have a function defined using rlang, how I can use purrr::map to use it with several variables ? , You need the !!! operator or using group_by_at
code :
library(tidyverse)


mean_by <- function(data, by, var) {
  data %>%
    group_by_at(by) %>% 
    summarise(avg = {{var}} %>% mean(na.rm =TRUE))
}


mtcars %>% 
  mean_by(by = vars(mpg,cyl),hp)
#> # A tibble: 27 x 3
#> # Groups:   mpg [25]
#>      mpg   cyl   avg
#>    <dbl> <dbl> <dbl>
#>  1  10.4     8   210
#>  2  13.3     8   245
#>  3  14.3     8   245
#>  4  14.7     8   230
#>  5  15       8   335
#>  6  15.2     8   165
#>  7  15.5     8   150
#>  8  15.8     8   264
#>  9  16.4     8   180
#> 10  17.3     8   180
#> # … with 17 more rows


# or


mean_by <- function(data, by, var) {
  data %>%
    group_by(!!!by) %>% 
    summarise(avg = {{var}} %>% mean(na.rm =TRUE))
}


mtcars %>% 
  mean_by(by = vars(cyl,disp),hp)
#> # A tibble: 27 x 3
#> # Groups:   cyl [3]
#>      cyl  disp   avg
#>    <dbl> <dbl> <dbl>
#>  1     4  71.1    65
#>  2     4  75.7    52
#>  3     4  78.7    66
#>  4     4  79      66
#>  5     4  95.1   113
#>  6     4 108      93
#>  7     4 120.     97
#>  8     4 120.     91
#>  9     4 121     109
#> 10     4 141.     95
#> # … with 17 more rows


Share : facebook icon twitter icon

Using pre-existing character vectors in quasiquotation of an expression with rlang


By : tbearfabo
Date : March 29 2020, 07:55 AM
may help you . In pre 0.5.0 dplyr the underlying framework for non-standard evaluation was lazyeval and required special consideration for strings. Hadley Wickham released a fundamentally new version of dplyr with a new underbelly called rlang which provides a more consistent framework for non-standard evaluation. This was version 0.70 - here's an explanation of why 0.6.0 was skipped - https://blog.rstudio.org/2017/06/13/dplyr-0-7-0/
The following now works without any special considerations:
code :
library("tidyverse")
my_cols <- c("Petal.Width", "Petal.Length")
iris %>%
  select(my_cols)
my_quos <- quos(Petal.Width, Petal.Length)
iris %>%
  select(!!!my_quos)
library("shiny")
library("tidyverse")
library("DT")
library("rlang")
shinyApp(
  ui = fluidPage(
    selectInput(
      "cols_to_show",
      "Columns to show",
      choices = colnames(iris),
      multiple = TRUE
    ),
    dataTableOutput("verb_table"),
    dataTableOutput("tidyeval_table")
  ),
  server = function(input, output) {
    output$verb_table <- renderDataTable({
      iris %>%
        select_(.dots = input$cols_to_show)

    })

    output$tidyeval_table <- renderDataTable({
      iris %>%
        select(!!!syms(input$cols_to_show))

    })
  }
)

Using purrr and dplyr: is rlang::sym the best way


By : Deg
Date : March 29 2020, 07:55 AM
will help you Short answer: yes.
If you want to map over columns, sym is a fine way to do it. Lionel Henry demonstrates sym in the draft vignette.
code :
library(dplyr)

x <- rlang::quo(cyl)
y <- rlang::sym("cyl")
identical(group_by(mtcars, !!x), group_by(mtcars, !!y))  # TRUE

how to use rlang inside purrr


By : ChrisLi
Date : March 29 2020, 07:55 AM
help you fix your problem I wan to get 2 data.frames with difference grouping by column , We can use group_by_at which can accept string argument.
code :
library(tidyverse)

c("hp", "cyl") %>% 
  tibble() %>% 
  magrittr::set_colnames("vars1") %>% 
  mutate(data = map(vars1,~mtcars %>% as_tibble)) %>% 
  mutate(res = map2(data,vars1,function(x,y){
    x %>% 
      group_by_at(y)
  }))

# A tibble: 2 x 3
#  vars1 data               res               
#  <chr> <list>             <list>            
#1 hp    <tibble [32 × 11]> <tibble [32 × 11]>
#2 cyl   <tibble [32 × 11]> <tibble [32 × 11]>
sym_fun <- function(x, y) {
  x %>%  group_by(!!sym(y))
}

c("hp", "cyl") %>% 
  tibble() %>% 
  magrittr::set_colnames("vars1") %>% 
  mutate(data = map(vars1,~mtcars %>% as_tibble)) %>% 
  mutate(res = map2(data,vars1,sym_fun))

using `rlang` quasiquotation with `dplyr::_join` functions


By : user3394581
Date : March 29 2020, 07:55 AM
To fix the issue you can do I am trying to write a custom function where I use rlang's quasiquotation. This function also internally uses dplyr's join functions. I have provided below a minimal working example that illustrated my problem. , We can convert to string with as_string
code :
dplyr::left_join(x = df_tally, y = df_mean,
            by = map_chr(group.by, rlang::as_string))
df_combiner <- function(data, x, group.by) {
  # check how many variables were entered for this grouping variable
  group.by <- as.list(rlang::quo_squash(rlang::enquo(group.by)))

  # based on number of arguments, select `group.by` in cases like `c(cyl)`,
  # the first list element after `quo_squash` will be `c` which we don't need,
  # but if we pass just `cyl`, there is no `c`, this will take care of that
  # issue
  group.by <-
    if (length(group.by) == 1) {
      group.by
    } else {
      group.by[-1]
    }

  # creating internal dataframe
  df <- dplyr::group_by(.data = data, !!!group.by, .drop = TRUE)

  # creating dataframes to be joined: one with tally, one with summary
  df_tally <- dplyr::tally(df)
  df_mean <- dplyr::summarise(df, mean = mean({{ x }}, na.rm = TRUE))

  # without specifying `by` argument, this works but prints a message I want to avoid
  #print(dplyr::left_join(x = df_tally, y = df_mean))

  # joining by specifying `by` argument (my failed attempt)
   dplyr::left_join(x = df_tally, y = df_mean, by = map_chr(group.by, rlang::as_string))

}
df_combiner(diamonds, carat, c(cut, clarity))
# A tibble: 40 x 4
# Groups:   cut [5]
#   cut   clarity     n  mean
#   <ord> <ord>   <int> <dbl>
# 1 Fair  I1        210 1.36 
# 2 Fair  SI2       466 1.20 
# 3 Fair  SI1       408 0.965
# 4 Fair  VS2       261 0.885
# 5 Fair  VS1       170 0.880
# 6 Fair  VVS2       69 0.692
# 7 Fair  VVS1       17 0.665
# 8 Fair  IF          9 0.474
# 9 Good  I1         96 1.20 
#10 Good  SI2      1081 1.04 
# … with 30 more rows

Why does purrr::map not support quasiquotation?


By : Arun
Date : March 29 2020, 07:55 AM
it should still fix some issue I think the problem is format does not support tidy dots -- you can use exec to force a function to be able to use them:
code :
library(tidyverse)
library(rlang)

set.seed(1)

nums <- rnorm(5L) #for some reason couldn't replicate your numbers
nums
#[1] -0.6264538  0.1836433 -0.8356286  1.5952808  0.3295078

dots <- exprs(digits = 2L)

map_chr(nums, ~exec(format, .x, !!!dots))
#[1] "-0.63" "0.18"  "-0.84" "1.6"   "0.33"
Related Posts Related Posts :
  • Loop in R to find the max of a matrix
  • Harvard citation format in R markdown
  • In R when using accessor "[", what is the default behavior when using on data frames?
  • histogram in R with for loop
  • Keep specific date range before and after a timestamp
  • Extract dates in various formats from string in R
  • Get (web) url for help documentation in R?
  • Mean of 3 dataframes with same dimensions
  • Calculate adstock using data.table
  • dataframe in R make empty and column after that
  • How to resolve the Error in f(x, ...) : unused argument (x)
  • a pair-case multiplication of variables/df (R)
  • How to label more breakpoints in Y axis ggplot2
  • How to remove rows if a list of columns is completely full of NAs (not removing the rows with at least one value other t
  • Create matrix from smaller matrices in R
  • source() path relative to the current script directory?
  • Plot time series with years in different columns
  • How to read a downloaded rds file
  • Scatter plot R for multiple values
  • Can I avoid evaluating inline Rmarkdown `r code` chunks?
  • Subtract values from different row
  • Getting an error when using gather to create clustered bar chart
  • Can you assign ggplot2 aestetics by calling characters in a vector?
  • Can someone please explain me this code? especially the role of "function x and [[x]]"?
  • Using colMeans in Rcpp
  • find column value and name based on minimum value in other column
  • Manually add labels separately (or together) by factor levels to barplot ggplot
  • Rmarkdown: Turn off title
  • How to switch every two elements in a vector in R?
  • User defined function to produce unique values of selected variables
  • ggplot plot averages of groups of varibales
  • Adding a polynomial term to a linear model
  • Overlay shapefile over Raster in Multiple plots
  • List of vectors slower in Julia than R?
  • How to create a dataframe from using data from another dataframe?
  • R: How to carry the last observed value forward, within the same unit of observation
  • R Compare one set of values with multiple sets
  • Scraping data from stats.nba.com, Getting Error in curl::curl_fetch_memory(url, handle = handle)
  • Error with factors as numeric in linear model
  • Gathering, averaging, and resulting
  • Read all Excel files with some sheets in R
  • what does "~0" mean in the R model matrix
  • How do I multiply an specific row in a matrix by a certain value?
  • How to check if all the observations are zero in longitudinal data set in R?
  • Return row(i) if two columns match
  • Plot_ly stacked barchart messes up y axis
  • Fill value in NETCDF in R
  • Customize Legend with discrete Data
  • How to have fixed size in funnel chart but dynamic hover text?
  • Allocate Rcpp List of n NumericMatrix
  • Plot discrete Raster data in R
  • Converting a 3D Array to a Dataframe
  • How I extract text between a string name and newline?
  • How can I compute the difference in consecutive rows for multiple columns?
  • List all the packages required in a script assuming package::function() in R
  • ggplot density plot for multiple groups
  • How to categorise a double (number) variable in R? I want to create a binomial category
  • Merging the content of several columns into one
  • How do i find the actual outliers in the boxplot in R
  • Changing the conditions to replace elements in a vector
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk