Home > Blockchain >  Understanding mutate function in dplyr
Understanding mutate function in dplyr

Time:09-22

I am given a snippet of R code which reads as below -

library(dplyr)
DF = data.frame('A' = 1:3, 'B' = 1:3)
DF %>% mutate(!!aa := A*2)

However I failed to run this code. But I am unable to understand what is !! is above line? And what is significance of :=?

Is it similar to DF %>% mutate('aa' := A*2)?

Any pointer will be highly appreciated.

CodePudding user response:

According to ?"!!"

It is sometimes useful to force early evaluation of part of an expression before it gets fully evaluated. The tidy eval framework provides several forcing operators for different use cases. The bang-bang operator !! forces a single object.

Unfortunately R is very strict about the kind of expressions supported on the LHS of =. This is why rlang interprets the walrus operator := as an alias of =. You can use it to supply names, e.g. a := b is equivalent to a = b.

If we need to do this on a more general case i.e. subsetting the column value from second data and create another column value as column name in first data

library(dplyr)
DF %>% 
    mutate(!! (DF1 %>% 
                  filter(X1 == 1) %>%
                   pull(X2)) := 'a')

-output

  A B BB
1 1 1  a
2 2 2  a
3 3 3  a

data

DF1 = data.frame(X1 = 1, X2 = 'BB')
  • Related