library(tidyverse)
df <- tibble(col1 = c(5, 2), col2 = c(6, 4), col3 = c(9, 9))
# # A tibble: 2 x 3
# col1 col2 col3
# <dbl> <dbl> <dbl>
# 1 5 6 9
# 2 2 4 9
I need to add columns 1 and 3. But the column names often change. So I can only use column numbers as opposed to the actual column name.
Attempt 1 works as expected.
Attempt 2 and 3 don't work.
What's wrong with my syntax? I can't use attempt 1 because next month the column names may be something else, but their relative positions will remain the same.
df %>% mutate(col4 = col1 + col3) # attempt 1
df %>% mutate(col4 = .[, 1] + .[, 3]) # attempt 2
df %>% {mutate(col4 = .[, 1] + .[, 3])} # attempt 3