- 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 change the sign of even number rows in column of a data.table object in R?
To change the sign of even number rows in a data.table object in R, we can follow the below steps −
First of all, create a data.table object.
Then, use vector multiplication with 1 and minus 1 to change the sign of even number rows.
Example
Create the data.table object
Let’s create a data.table object as shown below −
library(data.table) x<-sample(-5:5,30,replace=TRUE) 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: 2 2: 3 3: 5 4: 2 5: 5 6: -5 7: 2 8: 3 9: 0 10: 3 11: 3 12: -3 13: -1 14: -4 15: 5 16: 5 17: -1 18: -4 19: -5 20: -1 21: 4 22: 5 23: 2 24: 0 25: -3 26: 0 27: -2 28: 1 29: 4 30: -1 x
Change the sign of even number rows
Using vector multiplication with 1 and minus 1 to change the sign of even number rows in column x of data.table object DT −
library(data.table) x<-sample(-5:5,30,replace=TRUE) DT<-data.table(x) DT$x<-DT$x*c(1,-1) DT
Output
x 1: 2 2: -3 3: 5 4: -2 5: 5 6: 5 7: 2 8: -3 9: 0 10: -3 11: 3 12: 3 13: -1 14: 4 15: 5 16: -5 17: -1 18: 4 19: -5 20: 1 21: 4 22: -5 23: 2 24: 0 25: -3 26: 0 27: -2 28: -1 29: 4 30: 1 x
- Related Articles
- How to change the sign of even number rows in an R data frame column?
- How to change the sign of even number rows in single column matrix in R?
- How to find the number of times a variable changes its sign in an R data frame column?
- How to remove dollar sign from a column of a data.table object in R?
- How to find the column mean of first n number of rows in R data frame?
- How to change the column position of MySQL table without losing column data?
- How to extract unique rows by categorical column of a data.table object in R?
- How to change the column names and row names of a data frame in R?
- How can we change the data type of the column in MySQL table?
- How to count the number of duplicate rows in an R data frame?
- How to divide data.table object rows by number of columns in R?
- How to find the number of zeros in each column of a data.table object in R?
- How to divide data frame rows by number of columns in R?
- How to find the sum of rows of a column based on multiple columns in R data frame?
- How to repeat column values of a data.table object in R by number of values in another column?

Advertisements