简体   繁体   中英

Check the data type of a column in a data.frame in R

How to find the data type of a column in a data.frame?

I am using the below code, does it make sense? Am I getting the correct output.

for (f in feature.names) {

  if (class(train[[f]]) == "character") {
    count_c <- count_c + 1
  }
  if(class(train[[f]]) == "numeric"){
    count_numeric <- count_numeric + 1
  }
  if(class(train[[f]]) == "logical"){
    print(f)
    print(unique(train[[feature.names[count_n]]]))
    cat('\n')
    count_logic <- count_logic + 1
  }
  if(class(train[[f]]) == "integer"){
    count_int <- count_int + 1
  }
  count_n <- count_n + 1
}

Provided you have initialized your counters properly, your code should work. (A reproducible example would be nice ...) Following up on @akrun's suggestion,

table(sapply(yourdat, class))

should replace what you're doing, although something like

allClasses <- c("logical","integer","character","numeric")
s <- sapply(yourdat,class)
f <- factor(s,levels=allClasses)
table(f)

might work slightly better (will work if there are types not represented in the data set).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM