用R中数据框的多列中的数字替换单词
数据挖掘
r
数据框
工作室
数值
单词
2022-02-12 03:33:40
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
其它你可能感兴趣的问题
