如何将因子等级转换成 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 x2 1 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 y2 1 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 ...
广告