R 中的数字可以分为 3 种不同的类别
- Numeric:表示整数和浮点数。例如,123、32.43 等。
- Integer:仅表示整数,并用
L
标识。例如,23L、39L 等。 - Complex:表示带有虚部的复数。虚部用
i
标识。例如,2 + 3i、5i 等。
Numeric 数据类型
Numeric 数据类型是 R 中使用最频繁的数据类型。当您声明一个包含数字的变量时,它就是默认的数据类型。
您可以将任何类型的数字(带小数或不带小数)存储在 numeric
数据类型的变量中。例如,
# decimal variable
my_decimal <- 123.45
print(class(my_decimal))
# variable without decimal
my_number <- 34
print(class(my_number))
输出
[1] "numeric" [1] "numeric"
在此,my_decimal 和 my_number 变量都属于 numeric
类型。
Integer 数据类型
Integers 是一种 Numeric 数据类型,它可以接受不带小数的值。它主要用于当您确定变量将来不会包含任何小数时。
为了创建 integer
变量,您必须在值末尾使用后缀 L
。例如,
my_integer <- 123L
# print the value of my_integer
print(my_integer)
# print the data type of my_integer
print(class(my_integer))
输出
[1] 123 [1] "integer"
在此,变量 my_integer 包含值 123L
。值末尾的后缀 L
表明 my_integer 是 integer
类型。
Complex 数据类型
在 R 中,具有复数数据类型的变量包含带有虚部的数值。这可以通过在末尾使用 i
作为后缀来表示。例如,
# variable with only imaginary part
z1 <- 5i
print(z1)
print(class(z1))
# variable with both real and imaginary parts
z2 <- 3 + 3i
print(z2)
print(class(z2))
输出
[1] 0+5i [1] "complex" [1] 3+3i [1] "complex"
在此,变量 z1 和 z2 被声明为 complex
数据类型,其虚部由后缀 i
表示。
常见问题
如何将数字转换为 Numeric 值?
在 R 中,我们使用 as.numeric()
函数将任何数字转换为 numeric
值。例如,
# integer variable
a <- 4L
print(class(a))
# complex variable
b <- 1 + 2i
print(class(b))
# convert from integer to numeric
x <- as.numeric(a)
print(class(x))
# convert from complex to numeric
y <- as.numeric(b)
print(class(y))
输出
[1] "integer" [1] "complex" [1] "numeric" [1] "numeric" Warning message: imaginary parts discarded in coercion
这里,您可以看到在将 complex
数字转换为 numeric
值时,虚部被丢弃了。
如何将数字转换为 Complex 值?
您可以使用 as.complex()
函数将任何数字转换为 complex
值。例如,
# integer variable
a <- 4L
print(class(a))
# numeric variable
b <- 23
print(class(b))
# convert from integer to complex
y <- as.complex(a)
print(class(y))
# convert from numeric to complex
z <- as.complex(b)
print(class(z))
输出
[1] "integer" [1] "numeric" [1] "complex" [1] "complex"