如何在R中更改列名,当原始名称包含”$”时。

huangapple go评论74阅读模式
英文:

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 &lt;- data.frame(&#39;Foo$baR&#39; = c(1,2,3), check.names = FALSE)
df  
#&gt;   Foo$baR
#&gt; 1       1
#&gt; 2       2
#&gt; 3       3

df |&gt; janitor::clean_names()  
#&gt;   foo_ba_r
#&gt; 1        1
#&gt; 2        2
#&gt; 3        3

If it seems bit too aggressive for your liking, you can always replace that single character:

# to handle &quot;$&quot; as a literal string instead of a regular expression, 
# we can set `fixed = TRUE`
names(df) &lt;- gsub(&quot;$&quot;, &quot;_&quot;, names(df), fixed = TRUE)
df
#&gt;   Foo_baR
#&gt; 1       1
#&gt; 2       2
#&gt; 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)).

huangapple
  • 本文由 发表于 2023年7月14日 03:36:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76682711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定