Replacing words by numbers in multiple columns of a data frame in R

I want to replace the values in a data set (sample in the picture) using numbers instead of words, e.g., 1 instead of D, -1 instead of R, 0 for all other values. How can I do it with a loop? I know it can be done doing this instead:

(suppose d is index name)

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

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

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

Topic word dataframe numerical rstudio r

Category Data Science


I guess this is off-topic but here's a reproducible code:

#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))

Basically in new Response column, you check if R and assign -1, if not you check if D and assign 1; otherwise you assign 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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.