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?
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?
Share Improve this question edited Feb 5 at 16:16 jay.sf 73k8 gold badges63 silver badges125 bronze badges asked Feb 5 at 12:57 LuigiLuigi 4111 silver badge8 bronze badges 3 |3 Answers
Reset to default 2Change 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"
Using match:
df[, match(N, colnames(df)) ]
# [1] 1 2 3 4 5
You could define a special operator (but probably shouldn't).
> `@` <- \(d, x) d[[as.character(x)]]
>
> N <- 1000
> df@N
[1] 1 2 3 4 5
colnames(df) <- paste0("C", colnames(df))
then indexing as the answer suggests:df[[paste0("C", N)]]
returns the desired result. Good luck! – jpsmith Commented Feb 5 at 13:14