要在R中创建字符向量,我们可以将向量值括在双引号中,但是如果我们要使用数据帧的行值来创建字符向量,则可以使用as.character函数。例如,如果我们有一个数据帧df,则df第一行中的值可以使用as.character(df [1,])形成一个字符向量。
请看以下数据帧-
set.seed(3232) x<−sample(letters[1:26],25,replace=TRUE) y<−sample(LETTERS[1:26],25,replace=TRUE) z<−sample(c("Purity","Impurity","Crystal","Odorless","Chain Reaction"),25,replace=TRUE) a<−sample(c("High","Medium","Low"),25,replace=TRUE) df<−data.frame(x,y,z,a) df
输出结果
x y z a 1 w W Odorless Medium 2 r I Chain Reaction High 3 v T Impurity High 4 g H Impurity Medium 5 s I Purity Medium 6 i O Crystal Medium 7 y D Odorless High 8 m L Crystal Medium 9 m B Crystal Low 10 b E Crystal Medium 11 a G Chain Reaction Low 12 j R Odorless Low 13 d H Odorless Low 14 j V Impurity High 15 l Q Crystal High 16 j Z Impurity High 17 a F Chain Reaction Low 18 l L Odorless High 19 x I Odorless Low 20 y Z Crystal Medium 21 q K Chain Reaction High 22 t F Crystal Medium 23 j F Crystal High 24 y F Impurity Medium 25 l A Chain Reaction High
使用数据帧df的行创建字符向量-
as.character(df[1,]) [1] "w" "W" "Odorless" "Medium" as.character(df[2,]) [1] "r" "I" "Chain Reaction" "High" as.character(df[3,]) [1] "v" "T" "Impurity" "High" as.character(df[5,]) [1] "s" "I" "Purity" "Medium" as.character(df[10,]) [1] "b" "E" "Crystal" "Medium" as.character(df[12,]) [1] "j" "R" "Odorless" "Low" as.character(df[13,]) [1] "d" "H" "Odorless" "Low" as.character(df[15,]) [1] "l" "Q" "Crystal" "High" as.character(df[18,]) [1] "l" "L" "Odorless" "High" as.character(df[20,]) [1] "y" "Z" "Crystal" "Medium" as.character(df[25,]) [1] "l" "A" "Chain Reaction" "High" as.character(df[21,]) [1] "q" "K" "Chain Reaction" "High"
让我们看另一个例子-
G1<−sample(1:4,20,replace=TRUE) G2<−sample(c("Lower","Upper","Middle"),20,replace=TRUE) G3<−sample(c("Sensitive","Insenstive"),20,replace=TRUE) df_G<−data.frame(G1,G2,G3) df_G
输出结果
G1 G2 G3 1 2 Middle Sensitive 2 4 Middle Insenstive 3 2 Middle Sensitive 4 1 Upper Insenstive 5 3 Lower Insenstive 6 1 Upper Insenstive 7 3 Lower Sensitive 8 3 Lower Sensitive 9 3 Lower Sensitive 10 3 Lower Sensitive 11 1 Upper Insenstive 12 2 Lower Sensitive 13 4 Upper Insenstive 14 3 Middle Insenstive 15 2 Upper Sensitive 16 1 Upper Insenstive 17 4 Lower Insenstive 18 4 Middle Sensitive 19 2 Middle Sensitive 20 3 Middle Sensitive as.character(df_G[1,]) [1] "2" "Middle" "Sensitive" as.character(df_G[2,]) [1] "4" "Middle" "Insenstive" as.character(df_G[5,]) [1] "3" "Lower" "Insenstive" as.character(df_G[7,]) [1] "3" "Lower" "Sensitive" as.character(df_G[9,]) [1] "3" "Lower" "Sensitive" as.character(df_G[10,]) [1] "3" "Lower" "Sensitive" as.character(df_G[12,]) [1] "2" "Lower" "Sensitive" as.character(df_G[13,]) [1] "4" "Upper" "Insenstive" as.character(df_G[15,]) [1] "2" "Upper" "Sensitive"