0
假設我想將字符「6000」變成一個整數。我可以這樣做R錯誤NA錯誤
as.integer(6000)
但是,假設用戶輸入是「6 ***」。這給了我一個錯誤。如何將
as.integer(6***)
轉換爲NA。
假設我想將字符「6000」變成一個整數。我可以這樣做R錯誤NA錯誤
as.integer(6000)
但是,假設用戶輸入是「6 ***」。這給了我一個錯誤。如何將
as.integer(6***)
轉換爲NA。
你永遠不會寫as.integer(6000)
或as.integer(6***)
。
相反,你會寫
as.integer("6***")
或更可能
as.integer(str)
其中str
是一些文本通過用戶輸入提供。也許從文件中讀取等等。
在這種情況下,
as.integer(str)
確實會返回NA
如果str
是包含6***
的字符串。
> str = "6***" > as.integer(str) [1] NA Warning message: NAs introduced by coercion
是'6 ***'字符串?如果是這樣,R應該自動將它變成NA? –
如果它是一個字符,它需要在引號中。例如:'> as.numeric('6 ***') [1] NA'。在第一種情況下,'6000'已經是數字。你不得不做'as.numeric(as.character(6000))' – Maiasaura
你不能輸入'*'是一個二元運算符,這是一個函數,它在'*'的每一邊需要兩個參數。你的結構會在函數'as.integer()'被調用之前從解析器中拋出一個錯誤。 –