I need to find the column called "L1_Class" but only using the 'node' object defined first. Then, I'd like to add a column called "L1" that contains the same vector as "L1_Class". All in one short line if possible.
library(dplyr)
node <- "L1" # (in real life this is a folder name in a working directory) "../Mapping/VegType/L1"
# test dataframe
dat <- data.frame(L1_Class = c(rep("veg", 3),
rep("rock", 4),
rep("snow", 2)),
L2_tree = c(rep("conifer", 3),
rep("cottonwood", 4),
rep("snow", 2)),
L2_shrub = c(rep("alder", 3),
rep("willow", 4),
rep("snow", 2)),
L3_tree = c(rep("alder", 3),
rep("willow", 4),
rep("snow", 2)))
# this is what I need to add only using a function.
dat$L1 <- dat$L1_Class
# end dataframe (i hope).
head(dat)
# I need to find the column called "L1_Class" but only using the 'node' object.
# Then, I'd like to add a column called "L1" that contains the same vector as "L1_Class"
# All in one short line if possible.
dat_extra_col <- dat %>%
mutate( across(starts_with(gsub('_[^_]*$', "", node, fixed = TRUE))), .fns = list(node = ~gsub('_[^_]*$', "", ., fixed = TRUE)))
# or worse
dat_extra_col
dat %>% mutate(!!node := across(starts_with(gsub('_[^_]*$', "", node, fixed = TRUE))))
Thanks for any help!