我對R相當陌生,而且在遇到一個函數時遇到問題。我想將data.frame中的三列從字符轉換爲數字。它們大部分由數字組成,其中分佈有幾個「不可用」條目。我意識到這些,並且我希望他們在沒有看到警告的情況下強制要求新手,所以我使用了suppressWarnings()
函數。將字符變量強制轉換爲數字而不發出警告
這裏是我的代碼:
suppressWarnings(class(dataframe[,2]) <- "numeric")
suppressWarnings(class(dataframe[,3]) <- "numeric")
suppressWarnings(class(dataframe[,4]) <- "numeric")
print(apply(dataframe,2,class))
的是,該被打印的結果是我的問題:
1 2 3 4
"character" "character" "character" "character"
因此,它似乎並沒有被改變類!爲什麼是這樣?
當我做到這一點,但不影響的警告,就像這樣:
class(dataframe[,2]) <- "numeric"
class(dataframe[,3]) <- "numeric"
class(dataframe[,4]) <- "numeric"
print(apply(dataframe,2,class))
我得到的結果相同,但與警告消息:
1 2 3 4
"character" "character" "character" "character"
Warning messages:
1: In class(dataframe[, 2]) <- "numeric" : NAs introduced by coercion
2: In class(dataframe[, 3]) <- "numeric" : NAs introduced by coercion
3: In class(dataframe[, 4]) <- "numeric" : NAs introduced by coercion
所以它不是報警抑制是這樣的問題。它必須是apply()
函數,但我不明白爲什麼它會錯誤地顯示類。
任何意見或援助,將不勝感激!
你嘗試過'dataframe [,2] < - as.numeric(dataframe [,2])'嗎? – hrbrmstr
我確實嘗試過,並且得到了相同的輸出結果。 – MsTiggy
你可以粘貼一個'dput(dataframe)'輸出(甚至是'dataframe'的擴展'head')嗎? – hrbrmstr