簡體   English   中英

循環遍歷數據框列名 - R

[英]Loop through dataframe column names - R

我正在嘗試遍歷數據框的列名,並評估每列是哪個類。

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

我已經嘗試了一切,除了正確的方法..

PS:我嘗試這樣做是因為之后我必須為每個班級設置不同的條件。

要回答確切的問題並修復給定的代碼,請參見下面的示例

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類。

問題是遍歷數據幀的列,並詢問了一個關於遍歷數據幀的某些子集的附加問題。 我使用了 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]])))}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM