
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Index of Values in Data Table Column in R
To find the index of values in data.table object column in R if they occur once, we can follow the below steps −
First of all, create a data.table object.
Then, use which function along with duplicated function and single square brackets for subsetting to find the index of values in a column if they occur once.
Example 1
Create the data.table object
Let’s create a data.table object as shown below −
library(data.table) x<-sample(1:10,25,replace=TRUE) DT1<-data.table(x) DT1
Output
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x 1: 3 2: 7 3: 7 4: 2 5: 4 6: 8 7: 10 8: 4 9: 5 10: 9 11: 1 12: 5 13: 8 14: 10 15: 1 16: 10 17: 2 18: 1 19: 10 20: 10 21: 8 22: 2 23: 1 24: 10 25: 4 x
Find the index of values in a column if they occur once
Using which function along with duplicated function and single square brackets for subsetting to find the index of values in column x of data.table object DT1 if they occur once −
library(data.table) x<-sample(1:10,25,replace=TRUE) DT1<-data.table(x) which(!(DT1$x %in% DT1$x[duplicated(DT1$x)]))
Output
[1] 1 10
Example 2
Create the data.table object
Let’s create a data.table object as shown below −
library(data.table) y<-rpois(25,10) DT2<-data.table(y) DT2
Output
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
y 1: 9 2: 14 3: 7 4: 5 5: 11 6: 13 7: 8 8: 11 9: 9 10: 10 11: 6 12: 11 13: 10 14: 10 15: 14 16: 13 17: 13 18: 15 19: 9 20: 17 21: 11 22: 17 23: 20 24: 7 25: 12 y
Find the index of values in a column if they occur once
Using which function along with duplicated function and single square brackets for subsetting to find the index of values in column y of data.table object DT2 if they occur once−
library(data.table) y<-rpois(25,10) DT2<-data.table(y) which(!(DT2$y %in% DT2$y[duplicated(DT2$y)]))
Output
[1] 4 7 11 18 23 25