Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

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
like image 345
ah bon Avatar asked Jan 31 '26 02:01

ah bon


2 Answers

data.frame(column = colnames(df), index = seq_along(df))
#   column index
# 1      a     1
# 2      b     2
# 3      c     3
like image 81
r2evans Avatar answered Feb 02 '26 19:02

r2evans


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     
like image 35
Ritchie Sacramento Avatar answered Feb 02 '26 18:02

Ritchie Sacramento



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!