英文:
How to change column name in R when original name contains "$"
问题
我正在从一个API下载数据,并获得一个数据框,其列名包含"$"字符。我需要找到一种方法来更改这些名称,使它们不再包含"$"。有什么想法吗?
我尝试过使用colnames(EV)[3] = "DocID123"
,但这会更改所有具有相同名称的列名,留下了"$"之后的所有信息。感谢您的帮助!
英文:
I'm downloading data from an API and getting a data frame who's column names include the $ character. I need to find a way to change those names so they no longer include $. Any ideas?
I've tried using colnames(EV)[3] ="DocID123" but this changes every column name that has the same name before the $, and leaves all the info in the name that comes after the $. Thanks for the help!
答案1
得分: 2
一种选择是只需通过 janitor::clean_names()
处理该数据框,它将修复比名称中的 $
更多的问题:
df <- data.frame('Foo$baR' = c(1,2,3), check.names = FALSE)
df
#> Foo$baR
#> 1 1
#> 2 2
#> 3 3
df |> janitor::clean_names()
#> foo_ba_r
#> 1 1
#> 2 2
#> 3 3
如果这对您来说似乎有点过于激进,您总是可以替换那个单个字符:
# 要将“$”处理为文字字符串而不是正则表达式,我们可以设置 `fixed = TRUE`
names(df) <- gsub("$", "_", names(df), fixed = TRUE)
df
#> Foo_baR
#> 1 1
#> 2 2
#> 3 3
创建于2023年7月13日,使用 reprex v2.0.2
英文:
One option is just to feed that data.frame through janitor::clean_names()
, it will fix more issues than a $
in names:
df <- data.frame('Foo$baR' = c(1,2,3), check.names = FALSE)
df
#> Foo$baR
#> 1 1
#> 2 2
#> 3 3
df |> janitor::clean_names()
#> foo_ba_r
#> 1 1
#> 2 2
#> 3 3
If it seems bit too aggressive for your liking, you can always replace that single character:
# to handle "$" as a literal string instead of a regular expression,
# we can set `fixed = TRUE`
names(df) <- gsub("$", "_", names(df), fixed = TRUE)
df
#> Foo_baR
#> 1 1
#> 2 2
#> 3 3
<sup>Created on 2023-07-13 with reprex v2.0.2</sup>
答案2
得分: 1
在基础中,您可以执行names(your_data) = make.names(names(your_data))
。
英文:
In base, you can do names(your_data) = make.names(names(your_data))
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论