I want to create a new column with data from the last column of a data frame:
df <- matrix(1:4, ncol = 2) %>% as.data.frame()
df %>% mutate(V3 = .[[ncol(.)]] * 2)
Is there an easier to read and understand expression than .[[ncol(.)]]
?
Using across
and last_col
you could do:
library(dplyr, warn=FALSE)
df <- matrix(1:4, ncol = 2) %>% as.data.frame()
df %>%
mutate(across(last_col(), ~ .x * 2, .names = "V3"))
#> V1 V2 V3
#> 1 1 3 6
#> 2 2 4 8