userJT userJT - 7 months ago 63
R Question

How to fix spaces in column names of a data.frame (remove spaces, inject dots)?

After importing a file, I always try try to remove spaces from the column names to make referral to column names easier.

Is there a better way to do this other then using transform and then removing the extra column this command creates?

This is what I use now:

#tranform function does this, but requires some action
#remove dummy column
ctm2$dymmyvar <- NULL


There exists more elegant and general solution for that purpose: <- make.names(name.vector, unique=TRUE)

make.names() makes syntactically valid names out of character vectors. A syntactically valid name consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number.

Additionally, flag unique=TRUE allows you to avoid possible dublicates in new column names.