如何从列名中删除第一组数字?

发布于 2025-02-07 20:03:18 字数 339 浏览 0 评论 0原文

我有列名称,例如它们看起来像20819830_R1AR_U_STATIONARY2081974_F8AR_U。我试图摆脱列名中的第一组数字。我尝试使用此代码,

names(df)[1:2] <- gsub("^.*_","",names(df[,c(1:2)]))

但是当我使用此代码时,列名称转换为stastaryu。我可以看到该代码将所有内容删除,直到最后一个_如何更改代码,以便将所有内容删除到第一个_

I have column names, for example they look like this 20819830_r1ar_u_stationary and 2081974_f8ar_u. I am trying to get rid of the first set of numbers in the column names. I tried using this code

names(df)[1:2] <- gsub("^.*_","",names(df[,c(1:2)]))

but when I use this, the column names turn to stationary and u. I can see the code is removing everything up until the last _ how do I change the code so that it removes everything up until the first _.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怪我太投入 2025-02-14 20:03:18

使用Stringr的另一个选项。 str_remove将删除下面的第一组数字:

library(stringr)
str="20819830_r1ar_u_stationary"
str_remove(str, "^[0-9]+(?=_)_")
[1] "r1ar_u_stationary"

Another option using stringr. str_remove will remove the first set of digits that are followed by an underscore:

library(stringr)
str="20819830_r1ar_u_stationary"
str_remove(str, "^[0-9]+(?=_)_")
[1] "r1ar_u_stationary"
允世 2025-02-14 20:03:18

与其匹配。* - 一个或多个字符作为与任何字符匹配,它应该是一个或多个数字(\\ d+)字符串的开始(^

names(df)[1:2] <- sub("^\\d+_", "", names(df)[1:2])

Instead of matching .* - one or more characters as . matches any characters, it should be one or more digits (\\d+) from the start (^) of the string

names(df)[1:2] <- sub("^\\d+_", "", names(df)[1:2])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文