Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the column names of a Data Frame with sapply

Tags:

r

I want to get the columns names of a Data Frame with the following code:

DF <- data.frame(X=c(1,2), Y=c(3,4))
as.character(sapply(DF, names))

I've got the following:

"NULL" "NULL"

but I need the following result:

"X" "Y" 

How can I do this, thanks in advance.

like image 442
Ricardo UES Avatar asked Oct 03 '16 21:10

Ricardo UES


People also ask

How do I extract Dataframe column names?

You can get the column names from pandas DataFrame using df. columns. values , and pass this to python list() function to get it as list, once you have the data you can print it using print() statement.

How do I get column names from a data frame in R?

To access a specific column in a dataframe by name, you use the $ operator in the form df$name where df is the name of the dataframe, and name is the name of the column you are interested in. This operation will then return the column you want as a vector.

How do you find the columns of a data frame?

You can use the loc and iloc functions to access columns in a Pandas DataFrame. Let's see how. If we wanted to access a certain column in our DataFrame, for example the Grades column, we could simply use the loc function and specify the name of the column in order to retrieve it.

How do you access a column in an R data frame?

The column items in a data frame in R can be accessed using: Single brackets [] , which would display them as a column. Double brackets [[]] , which would display them as a list.


1 Answers

But there's a function to do it directly. See ?colnames

colnames(DF)
[1] "X" "Y"

In this case you could also do

names(DF)
[1] "X" "Y"

either way you don't need sapply to extract the column names.

If you name the rows names still only gives the column names:

rownames(DF)<-list("a","b")
DF
  X Y
a 1 3
b 2 4
names(DF)
[1] "X" "Y"

but the rownames function gets the row names for you:

rownames(DF)
[1] "a" "b"

If you had a list of data frames with the same number of columns you might perhaps use sapply with names.

If you want to obtain both the row and column names of the data frame, see dimnames.

like image 150
Glen_b Avatar answered Oct 04 '22 15:10

Glen_b