0

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!

  • 3
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. You code should only be changing one column name. Perhaps you have a complicated/nested structure. You could just be misinterpreting the printed output. – MrFlick Jul 13 '23 at 19:56
  • Yes, I think you're right! It's some kind of nested structure! But it's showing in my editor view as individual columns. In my console view I can see the nesting. I have a feeling my problem is in the code I'm using to retrieve the data from the API. EV_running <- data.frame() Page_number = c(0:2) for (N in Page_number) {res = GET(glue("http....") rawToChar(res$content) data = fromJSON(rawToChar(res$content)) EV <- as.data.frame(data) EV_running <- rbind(EV, EV_running) – Ryan Murtfeldt Jul 13 '23 at 23:18
  • @RyanMurtfeldt , it's almost impossible to suggest anything without having access to a sample response (JSON, not something parsed by jsonlite, often included in API documentation) or at least knowing which API you are targeting. Though you should hardly ever do something like `fromJSON(rawToChar(res$content))` ; if remote has not messed up headers, `res <- GET("http://httpbin.org/get"); content(res)` is enough to get a parsed result (unfortunately httpbin.org is not so stable anymore... ) – margusl Jul 14 '23 at 10:30
  • Awesome, thank you so much! – Ryan Murtfeldt Jul 14 '23 at 19:39

2 Answers2

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

Created on 2023-07-13 with reprex v2.0.2

margusl
  • 7,804
  • 2
  • 16
  • 20
1

In base, you can do names(your_data) = make.names(names(your_data)).

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294