2R一些类型
六类向量,其他R对象建立在原子向量之上。//怎么判断类型(v <-22 print(class(v))),输出numeric
1逻辑型:TRUE, FALSE //输出"logical"
2 Numeric(数字)12.3 // //输出"numeric"
3Integer(整型)2L //输出"integer"
4Complex(复合型)3 + 2i // //输出"complex"
5Character(字符'"good" //输出character
6Raw(原型) "Hello" 被存储为 48 65 6c 6c 6f //v <- charToRaw("Hello") print(class(v)) 输出“raw”
请注意,在R中,类的数量不仅限于上述六种类型。 例如,我们可以使用许多原子向量并创建一个数组,其类将成为数组
1Vectors 向量: 当你想用多个元素创建向量时,你应该使用c()函数,这意味着将元素组合成一个向量。
apple <- c('red','green',"yellow”)//print(apple) //"red" "green" "yellow"
//print(class(apple))// "character"
2Lists 列表:列表是一个R对象,它可以在其中包含许多不同类型的元素,如向量,函数甚至其中的另一个列表。
list1 <- list(c(2,5,3),21.3,sin) //print(list1)
当我们执行上面的代码,它产生以下结果
[[1]]
[1] 2 5 3
[[2]]
[1] 21.3
[[3]]
function (x) .Primitive("sin")
3Matrices 矩阵: a <- matrix(c('a','b','c','d','e','f'),2,3,TRUE)
或者M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
[,1] [,2] [,3]
[1,] "a" "b" "c"
[2,] "d" "e" "f"
4Arrays 数组
最简单1
a = array(c('green','yellow'))
> print(a)
[1] "green" "yellow"
多维
a = array(c('green','yellow'),dim=c(2几行,4几列,3几个))
print(a)
, , 1
[,1] [,2] [,3] [,4]
[1,] "green" "green" "green" "green"
[2,] "yellow" "yellow" "yellow" "yellow"
, , 2
[,1] [,2] [,3] [,4]
[1,] "green" "green" "green" "green"
[2,] "yellow" "yellow" "yellow" "yellow"
, , 3
[,1] [,2] [,3] [,4]
[1,] "green" "green" "green" "green"
[2,] "yellow" "yellow" "yellow" "yellow"
5Factors 因子
因子是使用向量创建的r对象。 它将向量与向量中元素的不同值一起存储为标签。 标签总是字符,不管它在输入向量中是数字还是字符或布尔等。 它们在统计建模中非常有用。
使用factor()函数创建因子。nlevels函数给出级别计数。
> apple_colors <- c('green','red','yellow','red','red','green')
> apple <- factor(apple_colors)
> print(apple)
[1] green red yellow red red green
Levels: green red yellow
print(nlevels(apple)) 3//知道不同值的个数
6Data Frames 数据帧
数据帧是表格数据对象。 与数据帧中的矩阵不同,每列可以包含不同的数据模式。 第一列可以是数字,而第二列可以是字符,第三列可以是逻辑的。 它是等长度的向量的列表。
使用data.frame()函数创建数据帧。
# Create the data frame.
BMI <- data.frame(
gender = c("Male", "Male","Female"),
height = c(152, 171.5, 165),
weight = c(81,93, 78),
Age = c(42,38,26)
)
print(BMI)
当我们执行上面的代码,它产生以下结果
gender height weight Age
1 Male 152.0 81 42
2 Male 171.5 93 38
3 Female 165.0 78 26

浙公网安备 33010602011771号