How to find mathematical set using a data frame column in R?

R ProgrammingServer Side ProgrammingProgramming

A mathematical set is a collection of unique elements or a collection of elements that are different from each other. If we want to find a mathematical set using a data frame column then we can simply use unique function.

For Example, if we have a data frame called df that contains a column say X then we can find the mathematical set using X with the help of below command −

unique(df$X)

Example 1

Following snippet creates a sample data frame −

x<-rpois(20,5)
df1<-data.frame(x)
df1

The following dataframe is created

   x
1  7
2  3
3  7
4  5
5  5
6  5
7  6
8  6
9  4
10 0
11 5
12 6
13 2
14 4
15 6
16 4
17 2
18 4
19 5
20 6

To find mathematical set using column x of df1 on the above created data frame, add the following code to the above snippet −

x<-rpois(20,5)
df1<-data.frame(x)
unique(df1$x)

Output

If you execute all the above given snippets as a single program, it generates the following Output −

[1] 7 3 5 6 4 0 2

Example 2

Following snippet creates a sample data frame −

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

The following dataframe is created

     y
1  -0.4
2   0.0
3   1.3
4   0.6
5  -1.2
6   0.4
7  -0.4
8   0.8
9   0.2
10  0.2
11  0.8
12  1.2
13 -1.6
14  2.2
15  0.9
16 -0.4
17 -0.3
18  0.2
19 -0.3
20  0.5

To find mathematical set using column y of df2 on the above created data frame, add the following code to the above snippet −

y<-round(rnorm(20),1)
df2<-data.frame(y)
unique(df2$y)

Output

If you execute all the above given snippets as a single program, it generates the following Output −

[1] -0.4 0.0 1.3 0.6 -1.2 0.4 0.8 0.2 1.2 -1.6 2.2 0.9 -0.3 0.5

Example 3

Following snippet creates a sample data frame −

z<-rpois(20,2)
df3<-data.frame(z)
df3

The following dataframe is created

   z
1  3
2  6
3  1
4  4
5  1
6  1
7  1
8  2
9  2
10 2
11 1
12 2
13 2
14 1
15 3
16 1
17 2
18 2
19 1
20 4

To find mathematical set using column z of df3 on the above created data frame, add the following code to the above snippet −

z<-rpois(20,2)
df3<-data.frame(z)
unique(df3$z)

Output

If you execute all the above given snippets as a single program, it generates the following Output −

[1] 3 6 1 4 2
raja
Updated on 02-Nov-2021 11:45:44

Advertisements