如何从R中的数据帧值创建字符向量?
要在R中创建字符向量,我们可以将向量值括在双引号中,但是如果要使用数据帧值创建字符向量,则可以使用as.character函数。例如,如果我们有一个数据帧df,则df中的所有值都可以使用as.character(df [])形成一个字符向量。
例1
x1<−letters[1:10]x2<−letters[11:20]
df1<−data.frame(x1,x2)
df1
输出结果
x1 x21 a k
2 b l
3 c m
4 d n
5 e o
6 f p
7 g q
8 h r
9 i s
10 j t
as.character(df1[])
[1] "c(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\")"
[2] "c(\"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\")"
is.vector(as.character(df1[]))
[1] TRUE
例2
set.seed(3232)y1<−sample(LETTERS[1:5],20,replace=TRUE)
y2<−sample(LETTERS[6:15],20,replace=TRUE)
y3<−sample(LETTERS[16:26],20,replace=TRUE)
df2<−data.frame(y1,y2,y3)
df2
输出结果
y1 y2 y31 E O U
2 B N U
3 C L P
4 A N Q
5 A I W
6 E M Y
7 E N P
8 B I Z
9 A G Z
10 B J W
11 D L R
12 D G R
13 B M U
14 D K W
15 B F S
16 A O Y
17 D K Z
18 A N Y
19 A O U
20 D K W
as.character(df2[])
[1] "c(\"E\", \"B\", \"C\", \"A\", \"A\", \"E\", \"E\", \"B\", \"A\", \"B\", \"D\", \"D\", \"B\", \"D\", \"B\", \"A\", \"D\", \"A\", \"A\", \"D\")"
[2] "c(\"O\", \"N\", \"L\", \"N\", \"I\", \"M\", \"N\", \"I\", \"G\", \"J\", \"L\", \"G\", \"M\", \"K\", \"F\", \"O\", \"K\", \"N\", \"O\", \"K\")"
[3] "c(\"U\", \"U\", \"P\", \"Q\", \"W\", \"Y\", \"P\", \"Z\", \"Z\", \"W\", \"R\", \"R\", \"U\", \"W\", \"S\", \"Y\", \"Z\", \"Y\", \"U\", \"W\")"
is.vector(as.character(df2[]))
[1] TRUE
例子3
z1<−sample(c("Purity","Impurity","Crystal"),20,replace=TRUE)z2<−sample(c("Chain Reaction","Odorless","Reactive"),20,replace=TRUE)
df3<−data.frame(z1,z2)
df3
输出结果
z1 z21 Impurity Reactive
2 Crystal Reactive
3 Impurity Chain Reaction
4 Purity Chain Reaction
5 Impurity Chain Reaction
6 Crystal Reactive
7 Crystal Chain Reaction
8 Impurity Reactive
9 Purity Odorless
10 Impurity Chain Reaction
11 Purity Odorless
12 Purity Chain Reaction
13 Impurity Odorless
14 Impurity Chain Reaction
15 Impurity Odorless
16 Purity Odorless
17 Impurity Chain Reaction
18 Crystal Reactive
19 Impurity Chain Reaction
20 Crystal Reactive
as.character(df3[])
[1] "c(\"Impurity\", \"Crystal\", \"Impurity\", \"Purity\", \"Impurity\", \"Crystal\", \"Crystal\", \"Impurity\", \"Purity\", \"Impurity\", \"Purity\", \"Purity\", \"Impurity\", \"Impurity\", \"Impurity\", \"Purity\", \"Impurity\", \"Crystal\", \"Impurity\", \"Crystal\")"
[2] "c(\"Reactive\", \"Reactive\", \"Chain Reaction\", \"Chain Reaction\", \"Chain Reaction\", \"Reactive\", \"Chain Reaction\", \"Reactive\", \"Odorless\", \"Chain Reaction\", \"Odorless\", \"Chain Reaction\", \"Odorless\", \"Chain Reaction\", \"Odorless\", \"Odorless\", \"Chain Reaction\", \"Reactive\", \"Chain Reaction\", \"Reactive\")"
is.vector(as.character(df3[]))
[1] TRUE
以上是 如何从R中的数据帧值创建字符向量? 的全部内容, 来源链接: utcz.com/z/345406.html