- Trending Categories
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 matrix in R?
To convert values greater than a threshold into 1 in matrix in R data frame, we can follow the below steps −
First of all, create a matrix.
Then, use ifelse function to convert values greater than a threshold into 1.
Example
Create the matrix
Let’s create a matrix as shown below −
M<-matrix(rnorm(50),ncol=2) M
Output
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
[,1] [,2] [1,] 1.35131510 1.37522054 [2,] -1.13345162 0.36286206 [3,] 0.63015182 -0.03290929 [4,] 0.92621651 1.31680036 [5,] -0.82421679 0.32648195 [6,] 0.97343371 -1.07267437 [7,] 1.64987699 -0.78395936 [8,] -1.26893096 -0.86729417 [9,] 1.43618275 -0.35711054 [10,] 0.47313589 1.33716595 [11,] -0.62682302 -0.11872530 [12,] -1.55459406 0.60669510 [13,] 0.71674609 0.38263617 [14,] 0.15818009 0.40835948 [15,] -0.63320156 -0.06941598 [16,] -0.18245803 -0.69972541 [17,] -0.83207399 -2.18994824 [18,] -0.50880490 -1.11029099 [19,] 0.09978232 0.84119858 [20,] -0.53728939 -0.42712942 [21,] 0.78737850 0.64063631 [22,] -0.54197740 1.52800265 [23,] 0.64130714 0.03383875 [24,] 0.54300424 -0.48200610 [25,] -0.91642041 -0.27952213
Convert values greater than a threshold to 1
Using ifelse function to convert values greater than a threshold into 1 in column 1 of matrix M −
M<-matrix(rnorm(50),ncol=2) M[,1]<-ifelse(M[,1]>0.5,1,M[,1]) M
Output
[,1] [,2] [1,] 1.00000000 1.37522054 [2,] -1.13345162 0.36286206 [3,] 1.00000000 -0.03290929 [4,] 1.00000000 1.31680036 [5,] -0.82421679 0.32648195 [6,] 1.00000000 -1.07267437 [7,] 1.00000000 -0.78395936 [8,] -1.26893096 -0.86729417 [9,] 1.00000000 -0.35711054 [10,] 0.47313589 1.33716595 [11,] -0.62682302 -0.11872530 [12,] -1.55459406 0.60669510 [13,] 1.00000000 0.38263617 [14,] 0.15818009 0.40835948 [15,] -0.63320156 -0.06941598 [16,] -0.18245803 -0.69972541 [17,] -0.83207399 -2.18994824 [18,] -0.50880490 -1.11029099 [19,] 0.09978232 0.84119858 [20,] -0.53728939 -0.42712942 [21,] 1.00000000 0.64063631 [22,] -0.54197740 1.52800265 [23,] 1.00000000 0.03383875 [24,] 1.00000000 -0.48200610 [25,] -0.91642041 -0.27952213
Advertisements