【R語言資料型別】深入瞭解 向量、矩陣、資料框、列表
阿新 • • 發佈:2019-01-10
R語言資料型別有向量、矩陣、資料框、列表。下面我們來深入瞭解下:
- vector 的劃分
R中的vector分為兩類,atomic和list,二者的區別在於,前者元素型別必須相同,後者可以不同。前者的代表是向量和矩陣,後者的代表是list和資料框。
建立向量、矩陣、資料框、列表
# atomic
a <- 1:5
b <- letters[1:5]
c <- 1:10
mat <- matrix(c,nrow=2)
# list
l <- list(a,b,c)
df <-data.frame(a,b)
結果:
> a
[1] 1 2 3 4 5
> b
[1] "a" "b" "c" "d" "e"
> c
[1] 1 2 3 4 5 6 7 8 9 10
>
> mat
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
> l
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] "a" "b" "c" "d" "e"
[[3]]
[1] 1 2 3 4 5 6 7 8 9 10
> df
a b
1 1 a
2 2 b
3 3 c
4 4 d
5 5 e
>
- is.vector
由於它們都是vector,所以用is.vector檢驗無法區分向量和列表。當然,也無法用as.vector將列表轉換成向量。
is.vector(a) # TRUE
is.vector(l) # TRUE
as.vector(l) # 仍然是list,,沒有改變
is.vector(mat) # FALSE
is.vector(df) # FALSE
大家可能注意到了,同樣是vector,矩陣和資料框用is.vector檢驗就返回的是FALSE,這說明is.vector也不是檢驗vector的,它的真正原理在於,檢查是否最多隻有一個屬性:name。即檢視其屬性,如果沒有屬性或者只有一個name屬性,才返回TRUE。
attributes(l) # NULL
attributes(a) # NULL
attributes(df) # 多個屬性names row.names class
attributes(mat) #只有一個dim
is.vector的這個功能我現在也不知道有什麼用,寫在這裡只是讓大家知道,不要亂用。
要想將list轉換成向量,可以用unlist函式
unlist(l)
as.atomic(l) # 報錯,沒有這個函式
as.list(a) # as.list函式是有的
as.vector的作用也不是把除了names以外的屬性全部刪掉,它的作用是,當作用物件是atomic時,去除它的所有屬性,如果是list則沒改變,用is.vector檢驗也返回FALSE。我們有時用unlist轉換後得到的向量是自帶名字的,如果不去掉會造成一些麻煩,所以as.vector的一個作用是去除向量的名字屬性。
# as.vector作用於list無效
vdf <- as.vector(df)
attributes(vdf) # 屬性沒有改變
is.vector(vdf) # FALSE
# 轉化資料框後向量帶有名字
(udf <- unlist(df))
attributes(udf) # 只有一個names屬性
vudf <- as.vector(udf)
attributes(vudf) # NULL
# 自己建立帶有名字的向量
aaa <- c(1,2,3)
attr(aaa,"names")<-letters[1:3]
aaa
as.vector(aaa)
as.numeric(aaa) # 數值型向量去掉名字還有這種方法
bbb <- c(letters[4:6])
attr(bbb,"names")<- letters[1:3]
bbb
as.vector(bbb)