Reputation: 461
It is a very basic question.How can you set the column names of data frame to column index? So if you have 4 columns, column names will be 1 2 3 4
. The data frame i am using can have up to 100 columns.
Upvotes: 0
Views: 90
Reputation: 887008
It is not good to name the column names with names that start with numbers. Suppose, we name it as seq_along(D)
. It becomes unnecessarily complicated when we try to extract a column. For example,
names(D) <- seq_along(D)
D$1
#Error: unexpected numeric constant in "D$1"
In that case, we may need backticks
or ""
D$"1"
#[1] 1 2 3
D$`1`
#[1] 1 2 3
However, the [
should work
D[["1"]]
#[1] 1 2 3
I would use
names(D) <- paste0("Col", seq_along(D))
D$Col1
#[1] 1 2 3
Or
D[["Col1"]]
#[1] 1 2 3
D <- data.frame(a=c(1,2,3),b=c(4,5,6),c=c(7,8,9),d=c(10,11,12))
Upvotes: 3
Reputation: 792
Just use names
:
D <- data.frame(a=c(1,2,3),b=c(4,5,6),c=c(7,8,9),d=c(10,11,12))
names(D) <- 1:ncol(D) # sequence from 1 through the number of columns
Upvotes: 1