我想将字符串匹配映射到具有缺失值的二维数据集的变量。
如果有使用map_df
或其他向量化方法的解决方案,我会很感兴趣。
输入:
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")
)
所需的输出:
[[1]]
match1 match2 match3
72 74 NA
[[2]]
match1 match2 match3
12 NA 146
[[3]]
match1 match2 match3
24 145 14
如您所见,“ a”与match1匹配, “ c”匹配到match2和 “ d”匹配到match3。
我尝试过的事情:
library(magrittr)
library(purrr)
l %>% map_df(~list(
match1 = ifelse(
test = grepl(pattern = " a",x = .),yes = gsub(pattern = " a",replacement = "",no = NA
),match2 = ifelse(
test = grepl(pattern = " c",yes = gsub(pattern = " c",match3 = ifelse(
test = grepl(pattern = " d",yes = gsub(pattern = " d",no = NA
)
))