I want to map string matches to variables with a 2 dimensional dataset with missing values.
I would be interested if there is a solution with map_df
or another vectorised approach.
Input:
list(
c(a = "72 a", b = "74 c"),
c(a = "12 a", b = "146 d"),
c(a = "24 a", bb = "145 c", cx = "14 d")
)
Desired output:
[[1]]
match1 match2 match3
72 74 NA
[[2]]
match1 match2 match3
12 NA 146
[[3]]
match1 match2 match3
24 145 14
As you can see, " a" Matches to match1, " c" Matches to match2 and " d" Matches to match3.
What i tried:
library(magrittr)
library(purrr)
l %>% map_df(~list(
match1 = ifelse(
test = grepl(pattern = " a", x = .),
yes = gsub(pattern = " a", replacement = "", x = .),
no = NA
),
match2 = ifelse(
test = grepl(pattern = " c", x = .),
yes = gsub(pattern = " c", replacement = "", x = .),
no = NA
),
match3 = ifelse(
test = grepl(pattern = " d", x = .),
yes = gsub(pattern = " d", replacement = "", x = .),
no = NA
)
))