準(zhǔn)備一個(gè)帶names的向量
a_vector <- c("a","b","c","d")
names(a_vector) <- c("A","B","C","D")
a_vector
## A B C D
##"a" "b" "c" "d"
將帶names的vector轉(zhuǎn)換為單列data.frame
as.data.frame() 是數(shù)據(jù)框掰茶,行名為原向量names剩拢,列名為原對(duì)象名稱蕴茴。
a_data.frame <- as.data.frame(a_vector)
View(a_data.frame)
將帶有行名的data.frame轉(zhuǎn)換為帶names的vector
方法一:as.vector()
as.vector() 并未將向量轉(zhuǎn)換為向量。畢竟是個(gè)數(shù)據(jù)框腋逆,不管單列還是多列內(nèi)容需要選定列旁壮。
b_vector <- as.vector(a_data.frame$a_vector)
b_vector ## 無names的向量
## [1] "a" "b" "c" "d"
class(b_vector)
## [1] "character"
names(b_vector) <- rownames(a_data.frame)
b_vector ##帶names的向量
## A B C D
## "a" "b" "c" "d"
方法二:dplyr::pull()
library(dplyr)
library(tibble)
c_vector <- a_data.frame %>%
rownames_to_column() %>% #將rownames轉(zhuǎn)到數(shù)據(jù)框內(nèi)监嗜,新列名為rowname
pull(var = a_vector, #將要轉(zhuǎn)換為向量的內(nèi)容
name = rowname # 將rowname列作為新向量的名稱
)
c_vector #帶names的向量
## A B C D
## "a" "b" "c" "d"