英文:
Use regular expression to change column names
问题
df的列名例如为:
split_the_tree1.zip.name, split_the_tree2.zip.region, split_the_tree3.zip.type
我想要删除所有在`.zip.`之前的部分,包括`.zip.`,最终得到列名:`name, region, type`
我尝试了以下代码:
gsub(".*\\.zip\\.", "", colnames(df))
gsub('\\*.zip\\*', '', colnames(df))
英文:
the df column names are for instance:
split_the_tree1.zip.name, split_the_tree2.zip.region, split_the_tree3.zip.type
I would like to remove everything that comes before '.zip.'
including the '.zip.'
To end up with column names: name, region, type
I tried something like this:
gsub(".*\zip\/", "", colnames(df))
gsub('*.zip', '', colnames(df))
答案1
得分: 4
colnames(df) <- gsub('.*zip.', '', colnames(df))
请注意我们使用的是.*
而不是*.
尽管快速完成此操作的方法是注意到您想要的名称仅存储为扩展名,因此使用tools::file_ext
函数
strings <- c("split_the_tree1.zip.name", "split_the_tree2.zip.region",
"split_the_tree3.zip.type")
tools::file_ext(strings)
[1] "name" "region" "type"
英文:
colnames(df) <- gsub('.*zip.', '', colnames(df))
Note that we have .*
and not *.
Although the quick way to do this is to note that the names you want are simply stored as extensions, hence use tools::file_ext
function
strings <- c("split_the_tree1.zip.name", "split_the_tree2.zip.region",
"split_the_tree3.zip.type")
tools::file_ext(strings)
[1] "name" "region" "type"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论