Zach
Zach

Reputation: 30321

Remove whitespace from data.frame names

I have a dataframe I pulled into R using sqlQuery. I'd like to strip all the whitespace and special characters out of the data.frame's names, but sqlQuery has no strip.white=TRUE option, so I was thinking of doing this with a regular expression.

This works for whitespace:

myNames <- c("Sample Selection Reason", "My ID")
myNames <- gsub('\\s+', '.', myNames )

What can I do about special characters?

Upvotes: 1

Views: 566

Answers (2)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162411

You might like make.names(), a base R function that "make[s] syntactically valid names out of character vectors."

myNames <- c("Sample Selection Reason", "My ID")
make.names(myNames)
# [1] "Sample.Selection.Reason" "My.ID"   

Upvotes: 8

Matthew Plourde
Matthew Plourde

Reputation: 44614

data.frame(...) corrects the names. For example

df.badnames <- data.frame(`1-2` = 1:2, check.names=FALSE)
df.fixed <- data.frame(df)

Upvotes: 2

Related Questions