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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
