R语言基础之数据类型

R语言基础

一、数据类型

  • 向量
  • 列表
  • 矩阵
  • 数组
  • 因子
  • 数据帧
这些对象中最简单的是向量对象,也称为六类向量。 

数据类型 示例 验证代码 输出结果
逻辑 TRUE, FALSE v <- TRUE ; print(class(v)); [1] "logical"
数字值 12.3, 5, 999 v <- 23.5 ; print(class(v)); [1] "numeric"
整数 2L, 34L, 0L v <- 2L ; print(class(v)); [1] "integer"
复数 3 + 2i v <- 2+5i ; print(class(v)); [1] "complex"
字符 ‘a’ , ‘“good”, “TRUE”, ‘23.4’ v <- "TRUE" ; print(class(v)); [1] "character"
原生 "Hello"存储值为: 48 65 6c 6c 6f v <- charToRaw("Hello"); print(class(v)); [1] "raw"


1.向量

使用 c() 函数,表示将元素组合成一个向量

> apple <- c('red','green',"yellow");
> print(apple);
[1] "red"    "green"  "yellow"
> print(class(apple));
[1] "character"

2.列表
使用list()函数,可以包含许多不同类型的元素

> 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")

3.矩阵
使用matrix()函数,可以使用向量输入到矩阵的方式来创建

> M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
> print(M)
     [,1] [,2] [,3]
[1,] "a"  "a"  "b" 
[2,] "c"  "b"  "a" 

> N = matrix( c('a','b','c','d','q','r','o','p','t'), nrow = 3, ncol = 3, byrow = TRUE)
> print(N)
     [,1] [,2] [,3]
[1,] "a"  "b"  "c" 
[2,] "d"  "q"  "r" 
[3,] "o"  "p"  "t" 

4.数组
使用array()函数,采用一个dim属性来创建所需维数(先穷尽行后穷尽列)

> a <- array(c('green','yellow'),dim = c(3,3,1,2,2))
> print(a)
, , 1, 1, 1


     [,1]     [,2]     [,3]    
[1,] "green"  "yellow" "green" 
[2,] "yellow" "green"  "yellow"
[3,] "green"  "yellow" "green" 


, , 1, 2, 1


     [,1]     [,2]     [,3]    
[1,] "yellow" "green"  "yellow"
[2,] "green"  "yellow" "green" 
[3,] "yellow" "green"  "yellow"


, , 1, 1, 2


     [,1]     [,2]     [,3]    
[1,] "green"  "yellow" "green" 
[2,] "yellow" "green"  "yellow"
[3,] "green"  "yellow" "green" 


, , 1, 2, 2


     [,1]     [,2]     [,3]    
[1,] "yellow" "green"  "yellow"
[2,] "green"  "yellow" "green" 
[3,] "yellow" "green"  "yellow"

5.因子
因子使用factor()函数创建。nlevels函数给出了级别的计数。

> apple_colors <- c('green','green','yellow','red','red','red','green')
> factor_apple <- factor(apple_colors)
> print(factor_apple)
[1] green  green  yellow red    red    red    green 
Levels: green red yellow
> print(nlevels(factor_apple))
[1] 3

6.数据帧
数据帧是表格数据对象,数据帧使用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



你可能感兴趣的:(R语言)