如何用数字替换 R 数据框中二分列中的单词?

r programmingserver side programmingprogramming更新于 2025/6/24 9:22:17

二分列可以用诸如"是/否"、"好/坏"、"对/错"等单词表示。要将这些单词替换为数字,例如 1 和 0,我们可以使用 ifelse 函数。

例如,如果我们有一个名为 df 的数据框,其中包含一个包含"是"和"否"值的"二进制"列,那么我们可以使用以下命令 − 将"是"替换为 1,将"否"替换为 0。

df$Binary<-ifelse(df$Binary=="Yes",1,0)

示例 1

以下代码片段创建了一个示例数据框 −

x<-sample(c("Yes","No"),20,replace=TRUE)
df1<-data.frame(x)
df1

创建以下数据框 −

    x
1  Yes
2  Yes
3  Yes
4  Yes
5   No
6  Yes
7  Yes
8  Yes
9  Yes
10 Yes
11 Yes
12  No
13 Yes
14  No
15  No
16 Yes
17  No
18 Yes
19 Yes
20 Yes

要将单词 Yes 替换为 1,将 No 替换为 0,请将以下代码添加到上述代码片段中 −

x<-sample(c("Yes","No"),20,replace=TRUE)
df1<-data.frame(x)
df1$x<-ifelse(df1$x=="Yes",1,0)
df1

输出

如果将上述所有代码片段作为单个程序执行,则会生成以下输出 −

   x
1  1
2  1
3  1
4  1
5  0
6  1
7  1
8  1
9  1
10 1
11 1
12 0
13 1
14 0
15 0
16 1
17 0
18 1
19 1
20 1

示例 2

以下代码片段创建了一个示例数据框 −

y<-sample(c("Good","Bad"),20,replace=TRUE)
df2<-data.frame(y)
df2

创建以下数据框 −

   y
1  Bad
2  Bad
3  Bad
4  Good
5  Good
6  Good
7  Good
8  Bad
9  Bad
10 Bad
11 Bad
12 Bad
13 Good
14 Bad
15 Good
16 Good
17 Good
18 Bad
19 Good
20 Good

要将单词 Good 替换为 1,将 Bad 替换为 0,请将以下代码添加到上述代码片段中 −

y<-sample(c("Good","Bad"),20,replace=TRUE)
df2<-data.frame(y)
df2$y<-ifelse(df2$y=="Good",1,0)
df2

输出

如果将上述所有代码片段作为单个程序执行,则会生成以下输出 −

   y
1  0
2  0
3  0
4  1
5  1
6  1
7  1
8  0
9  0
10 0
11 0
12 0
13 1
14 0
15 1
16 1
17 1
18 0
19 1
20 1

相关文章