How to find the index of values in data.table object column in R if they occur once?

R ProgrammingServer Side ProgrammingProgramming

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)

Output

[1] 4 7 11 18 23 25

Published on 10-Nov-2021 06:23:00