问题是循环遍历数据帧的列,另外一个问题是关于循环遍历数据帧的某些子集。我使用了 mtcars 数据集,因为它的数据列比 iris 数据集多。这提供了一个更丰富的例子。要遍历某些列子集,请在 for 循环中使用数值而不是使用列的名称。如果感兴趣的列是规则间隔的,则使用感兴趣的列创建一个向量。示例如下:
#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]])))}