- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert values greater than a threshold into 1 in column of a data.table object in R?
To convert values greater than a threshold into 1 in data.table object in R data frame, we can follow the below steps −
First of all, create a data.table object.
Then, use ifelse function to convert values greater than a threshold into 1.
Example
Create the data.table object
Let’s create a data.table object as shown below −
library(data.table) x<-runif(25,1,2) DT<-data.table(x) DT
Output
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x 1: 1.122051 2: 1.355193 3: 1.058128 4: 1.817999 5: 1.585387 6: 1.789302 7: 1.227816 8: 1.099774 9: 1.442783 10: 1.014045 11: 1.639609 12: 1.090935 13: 1.801839 14: 1.237378 15: 1.988733 16: 1.000113 17: 1.670561 18: 1.444453 19: 1.797164 20: 1.079578 21: 1.888196 22: 1.635946 23: 1.986531 24: 1.401219 25: 1.902608 x
Convert values greater than a threshold to 1
Using ifelse function to convert values greater than a threshold into 1 in column x of data.table object −
library(data.table) x<-runif(25,1,2) DT<-data.table(x) DT$x<-ifelse(DT$x>1.5,1,DT$x) DT
Output
x 1: 1.122051 2: 1.355193 3: 1.058128 4: 1.000000 5: 1.000000 6: 1.000000 7: 1.227816 8: 1.099774 9: 1.442783 10: 1.014045 11: 1.000000 12: 1.090935 13: 1.000000 14: 1.237378 15: 1.000000 16: 1.000113 17: 1.000000 18: 1.444453 19: 1.000000 20: 1.079578 21: 1.000000 22: 1.000000 23: 1.000000 24: 1.401219 25: 1.000000 x
Advertisements