1

I'm new to R and looking for an easy way to get rid of column names in a R dataframe and return the names to their index [1,2,3,4..]. Something like combining .iloc and reset_index in pandas. I need the colnames initially before returning them to index so it can't be a solution that involves the read in of the files. I also have 50+ columns so I'm trying to avoid any solutions that involve manually writing ['1', '2', '3'...] for all 50.

Simply put: Current column names: ['a', 'b', 'c' etc... 'zz'] Looking for: ['1', '2', '3'...]

So far I tried names (x) <-NULL but that returns colnames(x) = NULL

I'm sorry if this has been asked elsewhere but it feels like such a simple problem and I've searched everywhere.

Thankyou

Maya
  • 13
  • 3
  • 1
    Column names that begin with numbers are syntactically illegal, and while they can be used they need to be wrapped with backticks in future operations which generally makes things more tedious than it ought to be. You can try `names(x) <- make.names(seq_along(names(x)))` to make legal names, or just `names(x) <- seq_along(names(x))` if you must have digits (note all names are stored as character). – Ritchie Sacramento Aug 30 '23 at 03:15
  • 1
    What's the rationale for explicitly naming the columns 1,2,3..? You can already refer to the columns in an indexing operation like `x[c(1,2)]` without needing to manually set the names. There might well be a good reason for your particular circumstances, but it's not clear to me what the advantage would be. – thelatemail Aug 30 '23 at 03:27
  • @thelatemail for whatever reason another dataframe that I'm using uses that naming convention and it's easier to go that way than name them the way this dataframe is named (ENSEMBL) – Maya Aug 30 '23 at 03:52
  • 1
    @RitchieSacramento Thank you for the comment but I think the other solution works slightly better for my application! – Maya Aug 30 '23 at 03:53

1 Answers1

0

You can use colnames along with seq_len:

df <- data.frame(a = c(1, 2), b = c(3, 4), c = c(5, 6))
print("Original data frame:")
print(df)
colnames(df) <- as.character(seq_len(ncol(df)))
print("Modified data frame:")
print(df)

Output:

[1] "Original data frame:"
  a b c
1 1 3 5
2 2 4 6
[1] "Modified data frame:"
  1 2 3
1 1 3 5
2 2 4 6
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40