如何将因子水平转换为R中的字符?
要将因子级别转换为字符,我们可以通过访问包含因子值的数据框的列来使用as.character函数。例如,如果我们有一个数据框df,其中包含一个名为Gender的因子列,则可以将该列转换为as.character(df $Gender)的字符列。
示例
请看以下数据帧-
set.seed(121)x1<−as.factor(sample(LETTERS[1:5],20,replace=TRUE))
x2<−rnorm(20,1,0.4)
df1<−data.frame(x1,x2)
df1
输出结果
x1 x21 D 0.7827428
2 D 0.5519596
3 D 0.3852095
4 D 0.3349047
5 A 1.1618117
6 C 0.4082440
7 A 1.5988801
8 C 0.9368104
9 C 1.0383650
10 E 0.2883935
11 D 0.3859827
12 E 1.5254714
13 D 1.2963078
14 A 0.2446046
15 E 0.4702711
16 B 1.1655974
17 B 0.9342977
18 C 0.9110071
19 A 1.3317495
20 B 1.6616840
示例
str(df1)
输出结果
'data.frame': 20 obs. of 2 variables:$ x1: Factor w/ 5 levels "A","B","C","D",..: 4 4 4 4 1 3 1 3 3 5 ...
$ x2: num 0.783 0.552 0.385 0.335 1.162 ...
将x1转换为字符列-
df1$x1<−as.character(df1$x1)str(df1)
输出结果
'data.frame': 20 obs. of 2 variables:$ x1: chr "D" "D" "D" "D" ...
$ x2: num 0.783 0.552 0.385 0.335 1.162 ...
让我们看另一个例子-
示例
y1<−as.factor(sample(c("India","Canada","Russia"),20,replace=TRUE))y2<−rpois(20,3)
df2<−data.frame(y1,y2)
df2
输出结果
y1 y21 Russia 4
2 Canada 1
3 India 5
4 India 3
5 India 3
6 Canada 3
7 Canada 1
8 Canada 1
9 Canada 0
10 India 4
11 Canada 4
12 Canada 5
13 Canada 3
14 India 3
15 Russia 4
16 India 4
17 Canada 3
18 Russia 7
19 India 2
20 Canada 3
示例
str(df2)
输出结果
'data.frame': 20 obs. of 2 variables:$ y1: Factor w/ 3 levels "Canada","India",..: 3 1 2 2 2 1 1 1 1 2 ...
$ y2: int 4 1 5 3 3 3 1 1 0 4 ...
将y1转换为字符列-
df2$y1<−as.character(df2$y1)str(df2)
输出结果
'data.frame': 20 obs. of 2 variables:$ y1: chr "Russia" "Canada" "India" "India" ...
$ y2: int 4 1 5 3 3 3 1 1 0 4 ...
以上是 如何将因子水平转换为R中的字符? 的全部内容, 来源链接: utcz.com/z/345533.html