1

I'm looking to create an binary variable column that shows simply indicates whether or not an existing column is equal to "R" or "P". If it is equal, i would like the new column to read "1", and if there is a blank observation I would like it to read "0".

I would like this:

Person    Play       Key  
A           1         R
B           2         P
C           3         
D           4         R
E           5          

To become this:

Person    Play       Key      Indicator
A           1         R           1
B           2         P           1 
C           3                     0
D           4         R           1
E           5                     0

I have tried:

df$Indicator <- (df$Key == 'R' | 'P')

But that doesn't work. I get the error Error in df$Indicator <- (df$Key == 'R' | 'P')" : operations are possible only for numeric, logical or complex types

Besides I'm not sure that would provide the binary indicator I'm looking for.

2 Answers 2

2

Try any of these approaches. You were almost close as you were using a code like df$Indicator <- (df$Key == 'R' | 'P') but the proper form would be df$Indicator <- df$Key == 'R' | df$Key =='P'. That will produce TRUE/FALSE values, so you can use as.numeric() to make them 0/1. Here the code:

#Code 1
df$Indicator <- as.numeric(df$Key %in% c('R','P'))
#Code 2
df$Indicator <- as.numeric(df$Key == 'R' | df$Key== 'P')

Output:

  Person Play Key Indicator
1      A    1   R         1
2      B    2   P         1
3      C    3             0
4      D    4   R         1
5      E    5             0

Some data used:

#Data
df <- structure(list(Person = c("A", "B", "C", "D", "E"), Play = 1:5, 
    Key = c("R", "P", "", "R", "")), row.names = c(NA, -5L), class = "data.frame")

Another option would be (All credits to @ChuckP):

#Code3
df$indicator <- ifelse(df$Key == 'R' | df$Key== 'P', 1, 0)

Which will produce same output.

Sign up to request clarification or add additional context in comments.

2 Comments

As long as you're giving coices @Duck don't forget good old df$indicator <- ifelse(df$Key == 'R' | df$Key== 'P', 1, 0) `
@ChuckP You are right, I will add that code to the answer! Great suggestion!
1
expl <- data.frame(Person = LETTERS[1:5], Play = 1:5, Key = c("R", "R"," ", "P", " "))
expl$Indicator <- expl$Key == 'R' | expl$Key =='P'
print(expl)
expl$Indicator2 <- as.numeric(expl$Key == 'R' | expl$Key =='P')
print(expl)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.