Appropriate times to use cur_data() vs across() in dplyr 1.0

Viewed 474

Here is a situation where using cur_data() and across() yields the same result:

library(tidyverse)
by_cyl <- mtcars %>% group_by(cyl)
a <- summarise(by_cyl,head(cur_data(), 2)) 
b <- summarise(by_cyl,head(across(), 2)))
identical(a,b)
#TRUE

My question is what is the difference between these two functions? When are they interchangeable and when are they not?

1 Answers

I think there is some misunderstanding. across and cur_data() are not related/interchangeable because they both are for different purpose.

across is used to apply a function on multiple columns, cur_data returns the current data for a group without the grouping variable.

In the example shared when you are using across() it does nothing and returns data as it is.

For example,

library(dplyr)
mtcars %>% summarise(across())

returns the same mtcars dataset as it is because the default values in across are .cols = everything() and .fns = NULL. So it applies NULL function to all the columns.

I am not sure what output you were expecting in this case.

Related