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

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

r - Getting the column names of a Data Frame with sapply

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...