'indexing column name in the dataframe in r

> df
  A B C
1 1 2 3
2 4 5 6
3 7 8 9

This is an example from another stack over flow question. Actually, in my dataset, there are 301 columns.

I wonder How I can index the column name. For example, I want to extract A, B, and C as my 1st, 2nd, and 3rd columns in the df.

df[0,1]

I thought it would give me "A" because it is the first column's name. but the result was Not "A" but

numeric(0)

How can I index my column name by its location? (1st, 2nd, 3rd ... columns in the dataframe)



Solution 1:[1]

In R indexing starts from 1 (and not 0). Secondly, df is the dataframe to get the names of the columns you need to index names(df) or colnames(df).

df <- data.frame(A = 1:5, B = 1:5, C = 1:5)

#To get all the column names
names(df)
#[1] "A" "B" "C"

#To get the 1st column name
names(df)[1]
#[1] "A"

#To get 1st and 2nd column name
names(df)[1:2]
#[1] "A" "B"

#To get column names 1 to 3
names(df)[1:3]
#[1] "A" "B" "C"

#To get column names 1 and 3
names(df)[c(1, 3)]
#[1] "A" "C"

Solution 2:[2]

Alternatively via select()

library(dplyr)
df %>% select(1,3) %>% colnames()

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 Ronak Shah
Solution 2 Julian