How to extract column names of dataframes from within a list in R

I would like to extract (and change) the column names of dataframes within a list by indexing them (to use in a for loop).

For example this gives me the desired result

df_list <- list(df = data.frame(x = c(1,2,3), y = c(4,5,6))
colnames(df_list$df)
[1] "x" "y"

However the following does not:

df_list <- list(df = data.frame(x = c(1,2,3), y = c(4,5,6))
colnames(df_list[1])
NULL

How can I do this by referring to the index of the dataframe rather than its name

Edit: Solved by thelatemail’s comment

>Solution :

Just use double braket [[..]] to access single element in list in R.

The [..] method returns objects of class list while the [[..]] method returns objects whose class is determined by the type of their values (i.e. a dataframe in our case).

Leave a Reply