Search code examples
rdplyrtidyselect

What is the recommended alternative for the deprecated .data[[ ]] in mutate()?


As of tidyselect 1.2.0 the use of .data[[ ]] is now deprecated.

Now I wonder how you can alias a column while using a vector with the column name of the target column.

What I used to do:

mycolname <- 'cyl'
mtcars %>% mutate(newcol = .data[[mycolname]]) %>% head()
#                   mpg cyl disp  hp drat    wt  qsec vs am gear carb newcol
#Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4      6
#Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4      6
#Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1      4
#Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1      6
#Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2      8
#Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1      6

What I tried:

mtcars %>% mutate(newcol = across(.cols = all_of(mycolname), ~.x)) %>% head()
#                    mpg cyl disp  hp drat    wt  qsec vs am gear carb                                       newcol
# Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4      \033[38;5;246m# A tibble: 6 × 1\033[39m
# Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4                                          cyl
# Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1   \033[3m\033[38;5;246m<dbl>\033[39m\033[23m
# Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1                \033[38;5;250m1\033[39m     6
# Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2                \033[38;5;250m2\033[39m     6
# Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1                \033[38;5;250m3\033[39m     4
# Warning message:
# In format.data.frame(if (omit) x[seq_len(n0), , drop = FALSE] else x,  :
#   corrupt data frame: columns will be truncated or padded with NAs

Solution

  • These work:

    library(dplyr)
    mycolname <- "cyl"
    
    # 1
    mtcars %>% mutate(newcol = !!as.name(mycolname)) %>% head()
    
    # 2
    mtcars %>% mutate(newcol = !!sym(mycolname)) %>% head()
    
    # 3
    mtcars %>% mutate(newcol = pick(everything())[[mycolname]]) %>% head()
    

    Update

    Fixed.