0

I have following data

Sample_ID<-c("a1","a2","a3","a4","a5","a6")
Score<-c(100, 200, 300, 400, NA, NA)
DF<-data.frame(Sample_ID,Score)

How to create a new variable called Score_status where all the samples having NA (missing value) will be coded as 0 and those having scores will be coded as 1. I am looking for following output.

Sample_ID     Score    Score_status
a1             100      1
a2             200      1
a3             400      1
a4             NA       0
a5             NA       0

How to do this in R.

3 Answers 3

3

You can try:

DF$Score_status <- ifelse(is.na(DF$Score),0,1)

  Sample_ID Score Score_status
1        a1   100            1
2        a2   200            1
3        a3   300            1
4        a4   400            1
5        a5    NA            0
6        a6    NA            0
Sign up to request clarification or add additional context in comments.

5 Comments

Getting this error: Error in $<-.data.frame(*tmp*, Score_status, value = logical(0)) : replacement has 0 rows, data has 6
@Aryh Updated answer, just check the names of DF, you can be confused by score and Score.
Code golf: +!is.na(DF$Score).
@r2evans using partial matching +!is.na(DF$Sc) :)
@sindri_baldur yes, though since I have options(warnPartialMatchDollar=TRUE), that actually adds 51 characters (in a sense, due to the warning ;-).
2
DF$Score_status <- 1
DF$Score_status[is.na(DF$Score)] <- 0

#   Sample_ID Score Score_status
# 1        a1   100            1
# 2        a2   200            1
# 3        a3   300            1
# 4        a4   400            1
# 5        a5    NA            0
# 6        a6    NA            0

Comments

2

You could use transform, and convert !is.na to binary numbers using +.

DF <- transform(DF, Score_status=+!is.na(Score))
DF
#   Sample_ID Score Score_status
# 1        a1   100            1
# 2        a2   200            1
# 3        a3   300            1
# 4        a4   400            1
# 5        a5    NA            0
# 6        a6    NA            0

2 Comments

Wouldn't the not-so-concice as.integer() be better practice?
@sindri_baldur Who judges? + is faster.

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.