numeric 位於 base 包(package)。 說明
創建或強製類型為 "numeric" 的對象。 is.numeric 是對對象可解釋為數字的更一般測試。
用法
numeric(length = 0)
as.numeric(x, ...)
is.numeric(x)
參數
length |
指定所需長度的非負整數。 Double 值將被強製轉換為整數:提供長度不是 1 的參數是錯誤的。 |
x |
對象被強製或測試。 |
... |
傳入或傳出其他方法的進一步參數。 |
細節
numeric 與 double 相同。它創建指定長度的雙精度向量,每個元素等於 0 。
as.numeric 是通用函數,但必須為 as.double 編寫 S3 方法。它與 as.double 相同。
is.numeric 是 internal generic primitive 函數:您可以編寫方法來處理特定類的對象,請參閱InternalMethods 。它與 is.double 不同。因子由默認方法處理,並且有類 "Date" 、 "POSIXt" 和 "difftime" 的方法(所有這些方法都返回 false)。僅當類的基類型為 double 或 integer 並且值可以合理地視為數字時,is.numeric 的方法才應返回 true(例如,對它們進行算術有意義,並且應通過基類型進行比較) )。
值
對於 numeric 和 as.numeric 請參閱 double 。
如果 is.numeric 的參數是 mode "numeric" ( type "double" 或類型 "integer" )且不是因子,則 is.numeric 的默認方法返回 TRUE,否則返回 FALSE。即 is.integer(x) || is.double(x) 或 (mode(x) == "numeric") && !is.factor(x) 。
警告
如果 x 是 factor , as.numeric 將返回底層數字(整數)表示形式,這通常沒有意義,因為它可能與 factor levels 不對應。請參閱 factor 中的“警告”部分(以及下麵的第二個示例)。
S4方法
as.numeric 和 is.numeric 是內部 S4 通用的,因此可以通過 setMethod 為它們設置方法。
為了確保 as.numeric 和 as.double 保持一致,隻能為 as.numeric 設置 S4 方法。
名字注意事項
這是一個曆史異常現象R其浮點向量有兩個名稱,double和numeric(並且以前有real)。
double 是 type 的名稱。 numeric 是 mode 的名稱,也是隱式 class 的名稱。作為 S4 正式課程,請使用 "numeric" 。
潛在的混亂是R已經使用過base mode
"numeric"表示“雙精度或整數”,這與 S4 的用法相衝突。因此is.numeric測試模式,而不是類,但是as.numeric(這與as.double)強製類。
例子
## Conversion does trim whitespace; non-numeric strings give NA + warning
as.numeric(c("-.1"," 2.7 ","B"))
## Numeric values are sometimes accidentally converted to factors.
## Converting them back to numeric is trickier than you'd expect.
f <- factor(5:10)
as.numeric(f) # not what you might expect, probably not what you want
## what you typically meant and want:
as.numeric(as.character(f))
## the same, considerably more efficient (for long vectors):
as.numeric(levels(f))[f]
參考
Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.
也可以看看
相關用法
- R numeric_version 數字版本
- R noquote “無引號”字符串打印類
- R ns-dblcolon 雙冒號和三冒號運算符
- R nargs 函數的參數數量
- R ns-internals 命名空間內部結構
- R ns-reflect 命名空間反射支持
- R normalizePath 以規範形式表達文件路徑
- R ns-hooks 命名空間事件的鉤子
- R nchar 計算字符數(或字節數或寬度)
- R ns-load 加載和卸載命名空間
- R norm 計算矩陣的範數
- R name 名稱和符號
- R nrow 數組的行/列數
- R names 對象的名稱
- R ns-topenv 頂級環境
- R nlevels 因子的水平數
- R file.path 構造文件路徑
- R grep 模式匹配和替換
- R getwd 獲取或設置工作目錄
- R vector 向量 - 創建、強製等
- R lapply 對列表或向量應用函數
- R dump R 對象的文本表示
- R Sys.getenv 獲取環境變量
- R rank 樣本排名
- R getDLLRegisteredRoutines DLL 中 C/Fortran 例程的反射信息
注:本文由純淨天空篩選整理自R-devel大神的英文原創作品 Numeric Vectors。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
