【问题标题】:Loop through dataframe column names - R循环遍历数据框列名 - R
【发布时间】:2018-09-28 02:06:03
【问题描述】:

我正在尝试遍历数据框的列名,并评估每一列是哪个类。

for (i in columns(df)){
  class(df$i)
}

我已经尝试了一切,除了正确的方法..

PS:我正在尝试这样做,因为之后我必须为每个班级设置不同的条件。

【问题讨论】:

  • sapply(df, class)
  • for (i in 1:length(df)){ class(df[,i]) }
  • 不知道你以后要做什么操作,但是你熟悉dplyr::mutate_if或者dplyr::summarise_if的函数集吗?

标签: r loops dataframe


【解决方案1】:

要回答确切的问题并修复给出的代码,请参见下面的示例

df <- iris # data

for (i in colnames(df)){
   print(class(df[[i]]))
}
# [1] "numeric"
# [1] "numeric"
# [1] "numeric"
# [1] "numeric"
# [1] "factor"
  1. 需要使用colnames来获取df的列名。
  2. 如果您想知道每一列的类别,您可以使用df[[i]] 访问每一列。 df[i] 属于 data.frame 类。

【讨论】:

  • 是否可以在第一列以外的不同列(例如第 11 列)上开始循环?
【解决方案2】:

问题是循环遍历数据帧的列,另外一个问题是关于循环遍历数据帧的某些子集。我使用了 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]])))}

【讨论】:

  • 请提供一些解释以配合此代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-31
相关资源
最近更新 更多