Error in `select()`:
? In argument: `all_of(label_col)`.
Caused by error in `all_of()`:
! Can't subset elements that don't exist.
? Element `Label` doesn't exist.
Run `rlang::last_trace()` to see where the error occurred.
原文 | 中文解釋 | 涉及關鍵詞 |
---|---|---|
Error in select() | 報錯發生在 select() 函數中 | select() 是 dplyr 中用于選取列的函數 |
In argument: all_of(label_col) | 報錯出現在參數 all_of(label_col) 中 | 你在代碼中寫了 select(all_of(label_col)) |
Caused by error in all_of() | 錯誤是由 all_of() 函數導致的 | all_of() 用于從字符向量中精確選列 |
Can't subset elements that don't exist | 無法選取不存在的列 | 說明你想選的列名(“Label”)在數據框中找不到 |
Element "Label" doesn't exist | 列名 “Label” 不存在 | 雖然你看上去有,但在 R 看來不“存在” |
數據框列名里有兩個 "Label"
,R 默認不會自動重命名它們,而是視為 重復列名。
R 在讀取 Excel/CSV 表格時,允許存在重復的列名,但 dplyr::select()
和 all_of()
不能處理重復列名,會直接報錯。
如何確認錯誤
colnames(df) # 查看所有列名
which(duplicated(colnames(df))) # 返回重復的列位置
輸出將告訴你是否 "Label"
出現了兩次。
如何解決
方法 | 代碼 | 說明 |
---|---|---|
1. 刪除重復列 | df <- df[, !duplicated(colnames(df))] | 刪除重復列,只保留第一次出現的 Label |
2. 重命名沖突列 | colnames(df)[duplicated(colnames(df))] <- "Label_dup" | 將第二個 Label 改名為 Label_dup |
3. 查看真實列名 | unique(colnames(df)) 、nchar(colnames(df)) | 看看是不是 " Label" 、"Label " 等有空格 |
正確選取 Label 列的方法
修復后你可以這樣寫:
label_col <- "Label"
y <- df[[label_col]]
X <- df %>% select(-all_of(label_col)) # 選除 Label 的所有特征列
表格匯總錯誤解釋
錯誤英文 | 中文解釋 | 建議操作 |
---|---|---|
Can't subset elements that don't exist | 要選擇的列名不存在 | 用 colnames(df) 檢查是否真有該列名 |
Element "Label" doesn't exist | 名為 Label 的列不在數據框中 | 查重名列,或檢查是否拼錯 |
duplicated(colnames(df)) | 列名重復會導致 select 報錯 | 刪除重復列或重命名沖突列 |