如何解决Purre地图,带有rename_with
我正在尝试清除数据集的名称。我已经使用janitor::clean_names()
开始了。但是,我仍然有一个缩写,我想用下划线_
分开。我有使用rename_with(~str_replace(.x,"gh","gh_"),.cols = starts_with("gh"))
进行工作的代码,但是有很多缩写,因此,找到一种方法来map
或对该过程进行功能化将是一个很好的选择。
dat <- tibble(ghrisk_value = c(1,2),ghrisk_corrected = c(2,3),devpolicy_value = c(4,5),devpolicy_corrected = c(5,6))
# code works but not functionalized
dat %>%
rename_with(~str_replace(.x,.cols = starts_with("gh")) %>%
rename_with(~str_replace(.x,"dev","dev_"),.cols = starts_with("dev")) %>%
names()
# attempt at map...
abbr_words <- c("gh","dev")
map(dat,~rename_with(str_replace(.x,abbr_words,str_c(abbr_words,"_")))
解决方法
您不需要map()
。只需使用正则表达式语法"(?<=a|b|c)"
(与a
或b
或c
后面的位置匹配)并插入下划线即可。另外,starts_with()
可以将字符向量作为输入来匹配所有元素的并集。
abbr_words <- c("gh","dev")
pattern <- sprintf("(?<=%s)",str_c(abbr_words,collapse = "|"))
# [1] "(?<=gh|dev)"
dat %>%
rename_with(~ str_replace(.x,pattern,"_"),starts_with(abbr_words))
# # A tibble: 2 x 4
# gh_risk_value gh_risk_corrected dev_policy_value dev_policy_corrected
# <dbl> <dbl> <dbl> <dbl>
# 1 1 2 4 5
# 2 2 3 5 6
,
您可以reduce
上的单词替换为str_replace
abbr_words <- c("gh","dev")
dat %>%
rename_all( ~
reduce(abbr_words,~str_replace(.x,paste0('^',.y),paste0(.y,'_')),.init = names(dat))
)
# # A tibble: 2 x 4
# gh_risk_value gh_risk_corrected dev_policy_value dev_policy_corrected
# <dbl> <dbl> <dbl> <dbl>
# 1 1 2 4 5
# 2 2 3 5 6
,
使用地图,您将需要一个辅助功能,即real_func。 map将使用colnames(dat),并且一次只能使用一个colname。 Map需要一个函数real_func,第一个参数,即数据参数将在该函数之前,其余参数将在以后。 Repl_func一次将列名设为一,并获取缩写词的列表,对其进行循环并执行替换。最后,unlist要求返回扁平化的向量。
abbr_words <- c("gh","dev")
repl_func <- function(x,y){
for (i in y){
x <- str_replace(x,i,paste0(i,"_"))
}
return (x)
}
colnames(dat) <- unlist(map(colnames(dat),repl_func,abbr_words))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。