我试图循环遍历数据框的列名,并评估每个列所属的类别。
for (i in columns(df)){
class(df$i)
}
除了正确的方法,我尝试了所有的方法...
顺便说一句:我在这样做是因为之后我需要为每个类设置不同的条件。
要回答确切的问题并修复给定的代码,请参见以下示例
df <- iris # data
for (i in colnames(df)){
print(class(df[[i]]))
}
# [1] "numeric"
# [1] "numeric"
# [1] "numeric"
# [1] "numeric"
# [1] "factor"
colnames
函数来获取df
的列名。df[[i]]
来访问每一列。而df[i]
是data.frame
类型。#Similar to previous answer only with mtcars rather than iris data.
df2<-mtcars
for (i in colnames(df2)){print(paste(i," ",class(df2[[i]])))}
#An alternative that is as simple but does not also print the variable names.
df2<-mtcars
for (i in 1:ncol(df2)){print(paste(i," ",class(df2[[i]])))}
#With variable names:
df2<-mtcars
for (i in 1:ncol(df2)){print(paste(i," ",colnames(df2[i])," ",class(df2[[i]])))}
#Now that we are looping numerically one can start in column 3 by:
df2<-mtcars
for (i in 3:ncol(df2)){print(paste(i," ",colnames(df2[i])," ",class(df2[[i]])))}
#To stop before the last column add a break statement inside an if
df2<-mtcars
for (i in 3:ncol(df2)){
if(i>7){break}
print(paste(i," ",colnames(df2[i])," ",class(df2[[i]])))}
#Finally, if you know the columns and they are irregularly spaced try this:
UseCols<-c(2,4,7,9,10)
for (i in UseCols){print(paste(i," ",colnames(df2[i])," ",class(df2[[i]])))}
sapply()
对数据框df
中的每个变量执行函数class()
,返回一个向量,其中包含每个变量的类别。 - Sathishfor (i in 1:length(df)){ class(df[,i]) }
- Jorgedplyr::mutate_if
或dplyr::summarise_if
函数集合? - hpesoj626