用R中数据框的多列中的数字替换单词

数据挖掘 r 数据框 工作室 数值 单词
2022-02-12 03:33:40

我想使用数字而不是单词替换数据集中的值(图片中的样本),例如,对于所有其他值,而1不是D-1而不是。我怎样才能用循环来做到这一点?我知道可以这样做:R0

(假设d是索引名称)

d[d$Response == "R",]$Response = -1

d[d$Response == "D",]$Response = 1

... (other values code it and assign value of) = 0

在此处输入图像描述

1个回答

我想这是题外话,但这是一个可重现的代码:

#Preparing mocking data
>set.seed(123) #for reproducibility
>Party <- sample(c('D', 'N','R'), 10, replace = TRUE) #sample random values
>d <- data.frame(Party) #put values into a dataframe

# Here's how you substitute the values in just one line. This operation is vectorised.
>d$Response <- ifelse(d$Party=='R', -1, ifelse(d$Party=='D', 1, 0))

基本上在新Response列中,您检查是否R并分配-1,如果不是,则检查是否D并分配1;否则你分配 0。

> d
   Party Response
1      D        1
2      R       -1
3      N        0
4      R       -1
5      R       -1
6      D        1
7      N        0
8      R       -1
9      N        0
10     N        0