# R语言 数据类型

2022-06-16 14:37 更新

• 矢量
• 列表
• 矩阵
• 数组
• 因子
• 数据帧

Logical（逻辑型）TRUE, FALSE
```v <- TRUE
print(class(v))
```

```[1] "logical"
```
Numeric（数字）12.3，5，999
```v <- 23.5
print(class(v))
```

```[1] "numeric"
```
Integer（整型）2L，34L，0L
```v <- 2L
print(class(v))
```

```[1] "integer"
```
Complex（复合型）3 + 2i
```v <- 2+5i
print(class(v))
```

```[1] "complex"
```
Character字符'a' , "good", "TRUE", '23.4'
```v <- "TRUE"
print(class(v))
```

```[1] "character"
```
Raw（原型）"Hello" 被存储为 48 65 6c 6c 6f
```v <- charToRaw("Hello")
print(class(v))
```

```[1] "raw"
```

## Vectors 向量

```# Create a vector.
apple <- c('red','green',"yellow")
print(apple)

# Get the class of the vector.
print(class(apple))
```

```[1] "red"    "green"  "yellow"
[1] "character"
```

## Lists 列表

```# Create a list.
list1 <- list(c(2,5,3),21.3,sin)

# Print the list.
print(list1)
```

```[[1]]
[1] 2 5 3

[[2]]
[1] 21.3

[[3]]
function (x)  .Primitive("sin")
```

## Matrices 矩阵

```# Create a 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"
```

## Arrays 数组

```# Create an array.
a <- array(c('green','yellow'),dim = c(3,3,2))
print(a)
```

```, , 1

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

, , 2

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

## Factors 因子

```# Create a vector.
apple_colors <- c('green','green','yellow','red','red','red','green')

# Create a factor object.
factor_apple <- factor(apple_colors)

# Print the factor.
print(factor_apple)
print(nlevels(factor_apple))
```

```[1] green  green  yellow  red   red   red   green
Levels: green red yellow
# applying the nlevels function we can know the number of distinct values
[1] 3
```

## Data Frames 数据帧

```# 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
```

App下载