Maya
Maya

Reputation: 13

Simple way to set R column names as index

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

Upvotes: 1

Views: 405

Answers (1)

Sash Sinha
Sash Sinha

Reputation: 22360

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

Upvotes: 0

Related Questions