Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It some function dedicated to side effects with tibble and pipe-lining?

Tags:

r

dplyr

tidyverse

I am wondering if I can use some function like dplyr::select, dplyr::mutate or dplyr::transmute to invoke side effect functions? I have walk, but it is not from same family.

tibble::as.tibble(mtcars) %>%
  dplyr::transmute(colA = cyl * hp, colB = mpg * wt) %>%
  dplyr::mutate(., (function(.data, colA, colB){
    print(colA)
    print(colB)
    # invisible(.data)
    return(.data)
  })(.data = ., colA, colB))

I would like to use column names as arguments to my function for example.

like image 201
koralgooll Avatar asked Jan 21 '26 23:01

koralgooll


1 Answers

base::with gives you the access to column-as-variables that you want, and magrittr::%T>% lets you run a line of side effects and still pass the whole data frame down the pipe. Simple example:

library(dplyr)
library(magrittr)

mtcars %>% slice(1:3) %T>%
  with({print(mpg)
        print(cyl)}) %>%
  summarize_all(mean)
# [1] 21.0 21.0 22.8
# [1] 6 6 4
#    mpg      cyl     disp       hp     drat    wt     qsec        vs am gear carb
# 1 21.6 5.333333 142.6667 104.3333 3.883333 2.605 17.36333 0.3333333  1    4    3

Simplified version of your example:

mtcars %>%
  transmute(colA = cyl * hp, colB = mpg * wt) %T>%
  with({
    print(colA)
    print(colB)
  }) %>%
  head
#  [1]  660  660  372  660 1400  630 1960  248  380  738  738 1440 1440 1440 1640 1720 1840  264  208
# [20]  260  388 1200 1200 1960 1400  264  364  452 2112 1050 2680  436
#  [1] 55.0200 60.3750 52.8960 68.8010 64.3280 62.6260 51.0510 77.8360 71.8200 66.0480 61.2320
# [12] 66.7480 64.5290 57.4560 54.6000 56.4096 78.5715 71.2800 49.0960 62.2065 52.9975 54.5600
# [23] 52.2120 51.0720 73.8240 52.8255 55.6400 45.9952 50.0860 54.5690 53.5500 59.4920
#   colA   colB
# 1  660 55.020
# 2  660 60.375
# 3  372 52.896
# 4  660 68.801
# 5 1400 64.328
# 6  630 62.626

Note that with takes only one expr argument, so to do multiple things in one with you will need to use {} to enclose the statements.

like image 100
Gregor Thomas Avatar answered Jan 24 '26 16:01

Gregor Thomas