r

How to deal with a number as column name, using an object


I have received a dataset in which column names are numbers, like this:

df<- data.frame(firstvar = c(1:5),
                secondvar = c(15:19))
colnames (df) <- c(1000, 1500)

df

  1000 1500
1    1   15
2    2   16
3    3   17
4    4   18
5    5   19

I know that I need to use backticks to call each column:

 df$`1000`
 [1]  1  2  3  4  5

I would like to use the object N (which will be an argument in a function in my real program) and assign it to the (numeric) column name so that I could use it instead of manually typing '1000'. However, I am not able to make it work, as I get NULL as output.

What I tried (always got NULL as result):

N <- 1000

df$`N`
df$N
df$'N'

How I would like it to work:

N <- 1000

df$`N`
[1]  1  2  3  4  5

Is this possible?


Solution

  • Change N to character and use [[ to extract the column values.

    df[[as.character(N)]]
    [1] 1 2 3 4 5
    

    This works because although it was a number when you named it, the name implicitly changes to character after that.

    names(df)
    [1] "1000" "1500"