歡迎關(guān)注:oddxix 轉(zhuǎn)載請注明出處疮方,謝謝
變量分配R-對象和R對象的數(shù)據(jù)類型變?yōu)樽兞康臄?shù)據(jù)類型。有許多類型的R-對象。常用的有:
- 矢量
- 列表
- 矩陣
- 數(shù)組
- 因子
- 數(shù)據(jù)幀
這些對象的是最簡單的矢量對象并且這些原子矢量有六種數(shù)據(jù)類型蒜茴,也被稱為六類向量星爪。另外R-對象是建立在原子向量。
因此粉私,在R語言中的非惩缣冢基本的數(shù)據(jù)類型是R-對象,如上圖所示占據(jù)著不同類別的元素向量诺核。請注意R語言中類的數(shù)量并不只限于上述的六種類型抄肖。 例如,我們可以使用許多原子向量以及創(chuàng)建一個數(shù)組窖杀,它的類將成為數(shù)組漓摩。
向量
當(dāng)您希望使用多個元素創(chuàng)建向量,應(yīng)該使用c()函數(shù)入客,這意味著元素結(jié)合成一個向量管毙。
# Create a vector.
apple <- c('red','green',"yellow")
print(apple)
# Get the class of the vector.
print(class(apple))
當(dāng)我們上面的代碼執(zhí)行時,它產(chǎn)生以下結(jié)果:
[1] "red" "green" "yellow"
[1] "character"
列表
列表是R-對象桌硫,它里面可以包含多個不同類型的元素夭咬,如向量,函數(shù)铆隘,甚至是另一個列表卓舵。
# Create a list.
list1 <- list(c(2,5,3),21.3,sin)
# Print the list.
print(list1)
當(dāng)我們上面的代碼執(zhí)行時,它產(chǎn)生以下結(jié)果:
[[1]]
[1] 2 5 3
[[2]]
[1] 21.3
[[3]]
function (x) .Primitive("sin")
矩陣
矩陣是一個二維矩形數(shù)據(jù)集膀钠。它可以使用一個向量輸入到矩陣函數(shù)來創(chuàng)建边器。
# Create a matrix.
M = matrix( c('a','a','b','c','b','a'), nrow=2,ncol=3,byrow = TRUE)
print(M)
當(dāng)我們上面的代碼執(zhí)行時,它產(chǎn)生以下結(jié)果:
[,1] [,2] [,3]
[1,] "a" "a" "b"
[2,] "c" "b" "a"
數(shù)組
盡管矩陣限于兩個維度托修,數(shù)組可以是任何數(shù)目的尺寸大小忘巧。數(shù)組函數(shù)使用它創(chuàng)建維度的所需數(shù)量的屬性-dim。在下面的例子中睦刃,我們創(chuàng)建了兩個元素數(shù)組砚嘴,這是3×3矩陣。
# Create an array.
a <- array(c('green','yellow'),dim=c(3,3,2))
print(a)
當(dāng)我們上面的代碼執(zhí)行時涩拙,它產(chǎn)生以下結(jié)果:
, , 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"
因子
因子是使用向量創(chuàng)建的R對象际长。它存儲隨同該向量作為標(biāo)記元素的不同值的向量。 標(biāo)簽始終是字符兴泥,而不論它在輸入向量的是數(shù)字或字符或布爾等工育。它們在統(tǒng)計建模有用。
運(yùn)用 factor() 函數(shù)創(chuàng)建因子搓彻。nlevels 函數(shù)給出級別的計數(shù)如绸。
# 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))
當(dāng)我們上面的代碼執(zhí)行時嘱朽,它產(chǎn)生以下結(jié)果:
[1] green green yellow red red red yellow green
Levels: green red yellow
applying the nlevels function we can know the number of distinct values
[1] 3
數(shù)據(jù)幀
數(shù)據(jù)幀是表格數(shù)據(jù)對象。不像在數(shù)據(jù)幀的矩陣怔接,每一列可以包含不同的數(shù)據(jù)的模型搪泳。第一列可以是數(shù)字,而第二列可能是字符和第三列可以是邏輯扼脐。它與向量列表的長度相等岸军。
數(shù)據(jù)幀所使用 data.frame()函數(shù)來創(chuàng)建。
# 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)
當(dāng)我們上面的代碼執(zhí)行時瓦侮,它產(chǎn)生以下結(jié)果:
gender height weight Age
1 Male 152.0 81 42
2 Male 171.5 93 38
3 Female 165.0 78 26