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

后端 未结 1 1165
我在风中等你
我在风中等你 2020-12-11 18:59

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         


        
1条回答
  •  [愿得一人]
    2020-12-11 19:33

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

    0 讨论(0)
提交回复
热议问题