user3192175
user3192175

Reputation: 3

Converting data into binary within a data frame

This table is called 'temp'

   No. of times   Clear   Included    Percentage
         2           1        1           0.50
         4           0        1           0.60
         0           0        0           0.20

For example, if I have this data set, I want to be converting all numbers above 0 under the 'No. of times' column to a 1 and leaving the 0 as it is.

Overall I'm wanting a data set looking like this

    No. of times   Clear   Included    Percentage
         1           1        1           0.50
         1           0        1           0.60
         0           0        0           0.20

How can I do this?

Upvotes: 0

Views: 662

Answers (3)

Ricardo Saporta
Ricardo Saporta

Reputation: 55420

great place to use ifelse

 temp$`No. of times` <- ifelse(temp$`No. of times` > 0, 1, 0)

As an aside, you might want to use

names(temp) <- make.names(names(temp))

Upvotes: 3

Gavin Simpson
Gavin Simpson

Reputation: 174938

A trick, but

temp[ , "No. of times"] <- (temp[ , "No. of times"] > 0) + 0

will also do the operation you want. I say a trick, because the part in parentheses (temp[ , "No. of times"] > 0) evaluates to a logical which is then coerced to 0 or 1 through the addition with 0.

Upvotes: 2

Wilmer E. Henao
Wilmer E. Henao

Reputation: 4302

temp[ ,"No. of times"] <- sign(temp[ ,"No. of times"])

Upvotes: 5

Related Questions