Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
537 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...