Reputation: 409
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(.)]]
?
Upvotes: 1
Views: 186
Reputation: 1023
The answers above are more efficient but out of completeness, you can assign the last column name to a string then reference the name in the mutate function.
If you want to offset from the last column (eg. second to last column) you can insert the offset position in last_col()
argument like last_col(1)
library(dplyr)
df <- matrix(1:4, ncol = 2) %>% as.data.frame()
last_col <- df |> select(last_col()) |> names()
df |>
mutate(V3=.data[[last_col]]*2)
Upvotes: 1
Reputation: 78
If using dplyr::mutate()
is not a must, you could directly assign V3
after reversing the column order:
df <- matrix(1:4, ncol = 2) %>% as.data.frame()
df$V3 <- 2*rev(df)[[1]]
Upvotes: 2
Reputation: 125418
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
Upvotes: 5