Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for identical columns in a data frame in R

Tags:

dataframe

r

Suppose you have a data frame called data with two identical columns:

A B 1 1 2 2 3 3 4 4 

How can I check if these two columns are identical and return one logical value to indicate it? A very basic pseudocode is:

if(data$A == data$B) {    print("Column A and B are identical") } 

I have been messing around with this for a bit and haven't found a way to do it that doesn't seem unnecessarily convoluted. Thanks.

like image 831
tjnel Avatar asked Apr 10 '13 05:04

tjnel


People also ask

How do I find identical columns in R?

Use the duplicated() function to create a vector that indicates which columns are identical. Optionall, show the names of the duplicated columns using the colnames() function.

How do I check if two columns are the same in R?

We can compare two columns in R by using ifelse(). This statement is used to check the condition given and return the data accordingly.

How do you check if all columns are equal in R?

You can use the function all_equal from the package dplyr . The function returns TRUE if the two data frames are identical, otherwise a character vector describing the reasons why they are not equal.

How do you check if data are the same in R?

setequal() function in R Language is used to check if two objects are equal.


2 Answers

You could use identical

identical(DT[['A']],DT[['B']]) 
like image 92
mnel Avatar answered Sep 22 '22 14:09

mnel


You could use all():

> data <- data.frame(A=c(1,2,3,4), B=c(1,2,3,4)) > all(data$A == data$B) [1] TRUE 
like image 40
NPE Avatar answered Sep 25 '22 14:09

NPE