# R語言數據類型

R語言與其他編程語言(如C語言和Java)相反，變量不會被聲明爲某些數據類型。 變量被分配給R對象，並且R對象的數據類型轉變爲變量的數據類型。 有很多類型的R對象。 常用R對象是 -

• 向量
• 列表
• 矩陣
• 數組
• 因子
• 數據幀

R編程中，非常基本的數據類型是叫作向量的R對象，它們保存不同類的元素，如上所示。 請注意在R語言中，類型的數量不僅限於上述六種類型。 例如，我們可以使用許多原子向量並創建一個數組，其類型將成爲數組。

## 向量

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

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

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

## 列表

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

## 矩陣

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

## 數組

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

## 因子

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

## 數據幀

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