2

I'm working with a data frame similar to the extract below:

df <- data.frame(A=c("Some messy string to be used",222,0), 
                 B=c("Very important ? indicator from 2001", 888, 44),
                 C=c("001 This variable / makes no sense", 888, 44),
                 D=c("Geography", 1, 2))

I would like to use values in first row as column names, I'm using the code below:

names(df) <- make.names(df[1,])

Unfortunately, the syntax generates names in the format Xn, as illustrated below:

> names(df)
[1] "X3" "X3" "X1" "X3"

I understand that the utilised strings are to messy for make.names to be meaningfully converted. How can I force R to use those messy string in a more efficient manner? As a rule of thumb I would like to:

  1. Keep figures (as they correspond to time)
  2. Keep at least few first words from the text
  3. Ensure that the names are unique
  4. The whole solution have to be fairly generic as there is a lot of rubbish in the first row (usually empty spaces or special characters).
Konrad
  • 17,740
  • 16
  • 106
  • 167
  • 3
    You may need `unlist` i.e. `make.names(unlist(df[1,]))` The reason why you got `X1:X5` is `df` columns are `factor` and you got the numeric index after coercing, which was later converted by appending `X` with `make.unique` – akrun Jul 21 '15 at 09:25
  • 1
    @akrun, I would suggest that you post it as an answer as the suggested solution works fine. – Konrad Jul 21 '15 at 09:29

2 Answers2

6

You don’t need to use make.names at all — you can assign the strings directly. This works perfectly fine in R. You just need to backtick-quote the names when you try to use them as R names (e.g. after the $ operator):

names(df) = unlist(df[1,])
df$`Some messy string to be used`
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • @KonradRudloph thanks it works. The slight nuisance is the need to add the **``** when using the name but it's not a major task. – Konrad Jul 21 '15 at 09:35
  • @Konrad: of course you can also select the column by subsetting the data.frame without using `$`, e.g. `df[,"Some messy string to be used"]` – digEmAll Jul 21 '15 at 09:38
2

use stringsAsFactors = F in data.frame which will create columns as char instead of factors. then make names on it.

df <- data.frame(A=c("Some messy string to be used",222,0), 
             B=c("Very important ? indicator from 2001", 888, 44),
             C=c("001 This variable / makes no sense", 888, 44),
             D=c("Geography", 1, 2),stringsAsFactors = F)
names(df) <- make.names(df[1,])
names(df)
Sivaji
  • 164
  • 9