How to find the index of values in an R data frame column if they occur once?

R ProgrammingServer Side ProgrammingProgramming

To find the index of values in an R data frame column if they occur once, we can follow the below steps −

  • First of all, create a data frame.

  • 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

Create the data frame

Let’s create a data frame as shown below −

x<-sample(1:10,25,replace=TRUE)
df1<-data.frame(x)
df1

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

    x
1   5
2   3
3  10
4   1
5   9
6   8
7   8
8   7
9   4
10  6
11  1
12  6
13  5
14  5
15  7
16  5
17  1
18  2
19  1
20  3
21  7
22  7
23  9
24 10
25  1

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 frame df1 if they occur once −

x<-sample(1:10,25,replace=TRUE)
df1<-data.frame(x)
which(!(df1$x %in% df1$x[duplicated(df1$x)]))

Output

[1] 9 18

Example 2

Create the data frame

Let’s create a data frame as shown below −

y<-round(rnorm(25),1)
df2<-data.frame(y)
df2

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

     y
1   2.1
2  -1.0
3  -1.6
4   1.5
5   0.5
6   1.4
7   0.2
8   0.6
9   0.2
10  0.6
11  0.4
12  0.2
13  0.4
14  1.6
15  1.4
16 -1.6
17 -1.1
18  0.4
19  1.0
20  0.3
21  0.4
22 -0.7
23 -0.9
24 -1.6
25 -0.4

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 frame df2 if they occur once −

y<-round(rnorm(25),1)
df2<-data.frame(y)
which(!(df2$y %in% df2$y[duplicated(df2$y)]))

Output

[1] 1 2 4 5 14 17 19 20 22 23 25
raja
Updated on 15-Nov-2021 07:17:54

Advertisements