'Save all column names and its index pairs as a dataframe/dictionary

I tried to get column names and its index, and save the result as a dataframe or dictionary:

df <- data.frame(a=rnorm(10), b=rnorm(10), c=rnorm(10))

How could I do that? Thanks.

column index
a   1
b   2
c   3


Solution 1:[1]

Another option:

library(tibble)

enframe(names(df), "index", "column")

# A tibble: 3 x 2
  index column
  <int> <chr> 
1     1 a     
2     2 b     
3     3 c     

Solution 2:[2]

Here's a tidyverse option:

library(tidyverse)

df %>% 
  slice(1) %>% 
  pivot_longer(everything()) %>% 
  rownames_to_column("index") %>% 
  select(name, index)

Output

  name  index
  <chr> <chr>
1 a     1    
2 b     2    
3 c     3  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ritchie Sacramento
Solution 2 AndrewGB