rename_with()与str_replace()组合使用失败的原因是什么?
问题:替换数据框列名中的"Abundance."时出现"object '.' not found"错误
尝试替换数据框列名里的"Abundance.",代码如下:
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."))
运行后报错:
Error in vctrs::vec_size_common(string = string, pattern = pattern, replacement = replacement, :
object '.' not found
核心问题:str_replace()未接收到以"."传递的字符串参数,但参考示例能正常运行。
解决方法
错误根源在于rename_with()的第二个参数要求是函数对象,而非直接执行函数调用。你直接写str_replace(., ...)会立刻执行这个函数,此时.还没有被绑定到列名上,因此抛出"object '.' not found"错误。
正确写法有两种:
1. 使用匿名函数包裹str_replace
library(dplyr) library(stringr) rename_with(xx, function(col_name) str_replace(col_name, pattern = "Abundance.", replacement = ""), contains("Abundance."))
2. 使用dplyr支持的公式简写语法
用~定义函数,.代表传入的列名参数:
rename_with(xx, ~str_replace(., pattern = "Abundance.", replacement = ""), contains("Abundance."))
额外注意:精准匹配列名中的点
你的列名实际是Abundance..(两个点),如果要精准替换掉Abundance.(包含一个点),需要注意正则表达式中点是通配符,建议用fixed()匹配原始字符串,避免误匹配:
rename_with(xx, ~str_replace(., fixed("Abundance."), replacement = ""), contains("Abundance."))
运行后列名将变为Sequence、126、127N、127C,符合预期。
内容的提问来源于stack exchange,提问作者Pavel Shliaha
相关产品推荐
相关产品推荐

