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

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

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() 处理该数据框,它将修复比名称中的 $ 更多的问题:

  1. df <- data.frame('Foo$baR' = c(1,2,3), check.names = FALSE)
  2. df
  3. #> Foo$baR
  4. #> 1 1
  5. #> 2 2
  6. #> 3 3
  7. df |> janitor::clean_names()
  8. #> foo_ba_r
  9. #> 1 1
  10. #> 2 2
  11. #> 3 3

如果这对您来说似乎有点过于激进,您总是可以替换那个单个字符:

  1. # 要将“$”处理为文字字符串而不是正则表达式,我们可以设置 `fixed = TRUE`
  2. names(df) <- gsub("$", "_", names(df), fixed = TRUE)
  3. df
  4. #> Foo_baR
  5. #> 1 1
  6. #> 2 2
  7. #> 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:

  1. df &lt;- data.frame(&#39;Foo$baR&#39; = c(1,2,3), check.names = FALSE)
  2. df
  3. #&gt; Foo$baR
  4. #&gt; 1 1
  5. #&gt; 2 2
  6. #&gt; 3 3
  7. df |&gt; janitor::clean_names()
  8. #&gt; foo_ba_r
  9. #&gt; 1 1
  10. #&gt; 2 2
  11. #&gt; 3 3

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

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

确定