I have data as follows:
library(data.table)
dat <- fread("varA, varB
some_string a1
other_string a3
blabla a3_2")
renaming_list <- c(
some_name = "a1",
other_name = "a3")
I am probably overthinking this, but I would like to match var_B
with the naming list to make:
dat <- fread("varA, varB name
some_string a1 some_name
other_string a3 other_name
blabla NA")
How should I match these? I was previously using a code that uses non-exact matches,
dat[, panel_name:=apply(outer(renaming_list, varB, Vectorize(grepl)), 2, \(x)
if (any(x)) names(which(x)) else NA)]
but now I only want exact matches. How should I adapt this code?
CodePudding user response:
rl2 = setNames(names(renaming_list), renaming_list)
dat[, varB := rl2[varB]]
dat
# varA, varB
# <char> <char>
# 1: some_string some_name
# 2: other_string other_name
# 3: blabla <NA>
CodePudding user response:
With match
:
dat[, name := names(renaming_list)[match(varB, renaming_list)]]
varA, varB name
1: some_string a1 some_name
2: other_string a3 other_name
3: blabla a3_2 <NA>