R Program to find the unique rows in r data frame


March 8, 2022, Learn eTutorial
1233

How to create a data frame using two given vectors and display the duplicated elements and unique rows

Here we are explaining how to write an R program to create a data frame using two given vectors and display the duplicated elements and unique rows. Here we are using a built-in function data.frame() for this. A data frame is used for storing data tables which has a list of vectors with equal length. The data frames are created by function data.frame(), which has tightly coupled collections of variables. The syntax of this function is, 



data.frame(…, row.names = NULL, check.rows = FALSE,check.names = TRUE, fix.empty.names = TRUE,stringsAsFactors = default.stringsAsFactors()) 

Where dots(...) indicates the arguments are of either the form value or tag = value and row. name is a NULL or a single integer or character string.

How to create a data frame using two given vectors and display the duplicated elements and unique rows in the R program

Below are the steps used in the R program to create a data frame using two given vectors and display the duplicated elements and unique rows. In this R program, we directly give the data frame to a built-in function. Here we are using variables v1,v2 for holding different types of vectors, and V for holding created data frame. Call the function data.frame() for creating dataframe. For getting duplicate elements call the method like duplicated(v1v2) and for getting unique elements call it like unique(v1v2).

ALGORITHM

STEP 1: Assign variables v1,v2 with vector values and V for data frame

STEP 2: First print original vector values

STEP 3: Create a data frame from given vectors as data.frame(v1,v2)

STEP 4: Print the duplicate elements by calling duplicated(v1v2)

STEP 5: Print the unique elements by calling unique(v1v2)

R Source Code

                                          v1 = c(10,20,10,10,40,50,20,30)
v2= c(10,30,10,20,0,50,30,30)
print("Original data frame:")
V = data.frame(v1,v2)
print(v1v2)
print("Duplicate elements of the data frame:")
print(duplicated(v1v2))
print("Unique rows of the data frame:")
print(unique(v1v2))
                                      

OUTPUT

[1] "Original data frame:"
   a  b
1 10 10
2 20 30
3 10 10
4 10 20
5 40  0
6 50 50
7 20 30
8 30 30
[1] "Duplicate elements of the data frame:"
[1] FALSE FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE
[1] "Unique rows of the data frame:"
   a  b
1 10 10
2 20 30
4 10 20
5 40  0
6 50 50
8 30 30