Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - apply() not working when checking column class in a data.frame

I have a dataframe. I want to inspect the class of each column.

x1 = rep(1:4, times=5)
x2 = factor(rep(letters[1:4], times=5))
xdat = data.frame(x1, x2)

> class(xdat)
[1] "data.frame"
> class(xdat$x1)
[1] "integer"
> class(xdat$x2)
[1] "factor"

However, imagine that I have many columns and therefore need to use apply() to help me do the trick. But it's not working.

apply(xdat, 2, class)
         x1          x2 
"character" "character" 

Why cannot I use apply() to see the data type of each column? or What I should do?

Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You could use

sapply(xdat, class)
#     x1        x2 
# "integer"  "factor" 

using apply would coerce the output to matrix and matrix can hold only a single 'class'. If there are 'character' columns, the result would be a single 'character' class. To understand this check

 str(apply(xdat, 2, I))
 #chr [1:20, 1:2] "1" "2" "3" "4" "1" "2" "3" "4" "1" ...
 #- attr(*, "dimnames")=List of 2
 # ..$ : NULL
 # ..$ : chr [1:2] "x1" "x2"

Now, if we check

 str(lapply(xdat, I))
 #List of 2
 #$ x1:Class 'AsIs'  int [1:20] 1 2 3 4 1 2 3 4 1 2 ...
 #$ x2: Factor w/ 4 levels "a","b","c","d": 1 2 3 4 1 2 3 4 1 2 ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...