1

My dependent variable looks like this:

$ dpnm : int 1 1 0 0 0 0 0 0 0 0 ...

And I want to convert the 1s int "Yes" and the 0s into "No"

I have tried:

default$dpnm <- revalue(default$dpnm , c(1 = "Yes"))
default$dpnm <- revalue(default$dpnm , c(0 = "No"))

1
  • Maybe its good to store binary values as a logical vector with TRUE and FALSE. default$dpnm <- default$dpnm == 1 Commented Oct 11, 2022 at 10:19

1 Answer 1

2

In base R you can use boolean indexing:

default$dpnm[default$dpnm==0]  <- "No"
default$dpnm[default$dpnm==1]  <- "Yes"

Depending on what you are doing, it may make more sense to convert it to an ordered factor with labels:

default$dpnm  <- factor(
    default$dpnm, 
    levels = c(0,1), 
    labels = c("No", "Yes"),
    ordered = TRUE
)
Sign up to request clarification or add additional context in comments.

3 Comments

Your code works, but it looks risky to me, because the first line default$dpnm[default$dpnm==0] <- "No" changes the type of the column to character. That means the second line is comparing a character vector to a number in default$dpnm==1. As it happens, this gives the right answer, but I'd worry there are obscure cases of similar problems where it fails (e.g. because of rounding in the conversion). I'd recommend creating a new intermediate variable rather than modifying the column twice.
@user2554330 fair point - I think it is OK in a simple case like this but implicit type coercion is certainly worth keeping in mind. I'd be interested if you could find an example where it causes unexpected results.
There probably aren't any such cases, I just like to avoid code that makes me worry :-).

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.