我想快速浏览数据框中的列类,我创建了这个函数来打印列名并按类排列。我想让它告诉我不是类因子的列数。
columnsclass<-function (x){
a<-vector()
b<-vector(mode="character")
c<-vector
c=0
for (i in 1:dim(x)[2]){
a[i]<-paste(class(x[,i]),names(x)[i],sep="--")
if (class(x[,i])!= "factor"){
c<-c+1
b[c]<<-i
}}
#1st print
print(sort(a))
#2nd print
print(paste("columns that aren't factors are number:",paste(b,collapse=","),collapse=" "))
}
然而,当我运行它时,虽然代码已经有效,但它没有进行#2nd打印。
> columnsclass(cars)
[1] "numeric--dist" "numeric--speed"
[1] "columns that aren't factors are number: "
#it doesn't print the numbers of columns of class factor but if i run it separately ,it runs
> print(paste("columns that aren't factors are number:",paste(b,collapse=","),collapse=" "))
[1] "columns that aren't factors are number: 1,2"
答案 0 :(得分:1)
这是一个考虑到皮埃尔评论的函数,但也简化了a
的计算:
columnsclass <- function(x){
nm <- sapply(x, class)
a <- paste(nm, names(nm), sep = "--")
b <- which(!sapply(x, is.factor))
# 1st print
print(sort(a))
# 2nd print
print(paste("columns that aren't factors are number:",
paste(b, collapse = ","), collapse = " "))
}
> columnsclass(cars)
[1] "numeric--dist" "numeric--speed"
[1] "columns that aren't factors are number: 1,2"
答案 1 :(得分:1)
str
功能怎么样?
library(datasets)
data(iris)
str(iris)