为什么 rename_with() 和 str_replace() 组合失败?

问题描述 投票:0回答:2

我正在尝试取代“丰富”。在我的小标题中的列名中。我正在使用以下方法:

一起使用 dplyr rename_at 和 stringr str_replace 重命名列时出错

xx <- structure(list(Sequence = c("HSEAATAQR", "GAAAHPDSEEQQQR"), Abundance..126 = c(12.3, 12.2), Abundance..127N = c(17.7, 13.5), Abundance..127C = c(11.9, 11.3)), row.names = 1:2, class = "data.frame") 
rename_with(xx, str_replace(., pattern = "Abundance.", replacement = ""), contains("Abundance."))

我收到错误:“vctrs::vec_size_common 中的错误(字符串 = 字符串,模式 = 模式,替换 = 替换,: 目的 '。'未找到”

我理解这意味着 str_replace() 函数没有接收我试图以“.”形式传递给它的字符串参数,但它似乎在上面提到的示例中工作

一起使用 dplyr rename_at 和 stringr str_replace 重命名列时出错

r dplyr
2个回答
0
投票
library(tidyverse)

替代方案1:

xx %>% 
  rename_with(~ str_replace(.x, pattern = "Abundance.", replacement = ""),
              contains("Abundance."))

替代方案2:

xx %>% 
  rename_with(~ str_remove(.x, "Abundance.."),
              contains("Abundance.."))

0
投票

您缺少

~
操作员:

xx %>% 
  rename_with(~str_replace(., pattern = "Abundance.", replacement = ""), contains("Abundance."))
© www.soinside.com 2019 - 2024. All rights reserved.