Linsey Marie Avila
Linsey Marie Avila

Reputation: 11

Assign value in one column if character in other column is x in R

I am trying to assign a specific interger/number in a column if the character in another column is x. I have 5 characters which repeat down the column, and in a new column I need to assign a number to each repeating character. Basically each of the 5 characters has a specific number that needs to go in the new column. Please help!

Upvotes: 1

Views: 667

Answers (1)

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

Here are two solutions to what I think is your task (a little difficult to judge as you do not provide any specifica data). Let's assume this is (like) your data:

 df <- data.frame(col1 = sample(LETTERS[1:5], 10, replace = T))

Solution 1: base R

df$new <- ifelse(df$col1 == "A", 1,
                 ifelse(df$col1 == "B", 2,
                        ifelse(df$col1 == "C", 3,
                               ifelse(df$col1 == "D", 4, 5))))

Solution 2: dplyr

library(dplyr)
df$new <- df %>% 
  mutate(col1 = case_when(col1 == "A" ~ 1,
                          col1 == "B" ~ 2,
                          col1 == "C" ~ 3,
                          col1 == "D" ~ 4,
                          TRUE        ~ 5))

The results are identical:

df
   col1 new
1     E   5
2     C   3
3     D   4
4     C   3
5     A   1
6     E   5
7     B   2
8     A   1
9     B   2
10    E   5

Upvotes: 1

Related Questions