You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中将文件名指定部分设为数据框列名?

修改数据框第三列列名为去后缀的文件名

基础R解决方案

1. 提取去后缀的文件名

推荐用tools包的内置函数,比手动拆分更稳妥:

# 定义文件名
filename <- "ABCD0001-01.filt"
# 去除.filt后缀
new_colname <- tools::file_path_sans_ext(filename)

如果你一定要用str_split_fixed,可以这样写(注意正则中点号需要转义):

library(stringr)
new_colname <- str_split_fixed(filename, "\\.filt", n = 2)[, 1]

2. 修改第三列列名

假设你的数据框名为df,直接通过列索引修改:

colnames(df)[3] <- new_colname

tidyverse(dplyr)解决方案

如果习惯用tidyverse生态,用dplyr的rename_with更符合管道风格:

library(dplyr)
library(stringr)

filename <- "ABCD0001-01.filt"
new_colname <- str_remove(filename, "\\.filt$")

# 替换第三列列名
df <- df %>%
  rename_with(~ new_colname, 3)

内容的提问来源于stack exchange,提问作者2__1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 08:09:17