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
360 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 Answer

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 ...

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

...