R 语言数字
数字
R 语言中有三种数字类型:
numeric(数字)integer(整数)complex(复杂的)
数字类型的变量是在为其赋值时创建的:
实例
x <- 10.5 # numericy <- 10L # integerz <- 1i # complex
Numeric
数字数据类型是 R 语言中最常见的类型,它包含任何带或不带小数的数字,如:10.5, 55, 787:
实例
x <- 10.5y <- 55# Print values of x and yxy# Print the class name of x and yclass(x)class(y)
Integer
整数是没有小数的数字数据。当您确定永远不会创建一个应该包含小数的变量时,可以使用此选项。要创建 integer 整数变量,必须在整数值后使用字母 L:
实例
x <- 1000Ly <- 55L# Print values of x and yxy# Print the class name of x and yclass(x)class(y)
Complex
complex 是用一个 "i" 作为虚部写的:
实例
x <- 3+5iy <- 5i# Print values of x and yxy# Print the class name of x and yclass(x)class(y)
类型转换
您可以使用以下功能从一种类型转换为另一种类型:
- as.numeric()
- as.integer()
- as.complex()
实例
x <- 1L # integery <- 2 # numeric# convert from integer to numeric:a <- as.numeric(x)# convert from numeric to integer:b <- as.integer(y)# print values of x and yxy# print the class name of a and bclass(a)class(b)