0

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?

1
  • 2
    Hi, you are using the terms data.frame, data.table and table interchangeably, which is a mistake. They are distinct classes of R objects and you should not use them interchangeably. Commented Jan 14, 2014 at 22:49

3 Answers 3

5
temp[ ,"No. of times"] <- sign(temp[ ,"No. of times"])
Sign up to request clarification or add additional context in comments.

2 Comments

I tried your way but the output was a list of all the numbers. I want the numbers to be incorporated back within the data table format I've shown above. How is this done?
Sounds like you only ran the right part. sign(temp[ ,"No. of times"]) If you type print(temp) you will see the whole thing :)
3

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))

3 Comments

I tried your first method with ifelse, but the output was a list of all the numbers. I want the numbers to be incorporated within the data table format I've shown above. How is this done?
Did you run what I have above? It is getting assigned back into temp, so use print(temp). Also, is your object a data.table or a data.frame (are you calling library(data.table) in your code?)
No prob, glad it helped. Personally, I like @WilmerEHenaoH 's method better. You might want to give it a check mark ;)
2

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.

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.