Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if variables are in a one-to-one mapping

Tags:

r

Suppose I have a data-frame in R with two variables that I will call A and B. I want to check if these two variables are in a one-to-one mapping). For example, consider the following data frame:

DF <- data.frame(A = c(0,2,0,1,2,1,0,1,1,1),
                 B = c('H','M','H','W','M','W','H','W','W','W'));

DF;
   A B
1  0 H
2  2 M
3  0 H
4  1 W
5  2 M
6  1 W
7  0 H
8  1 W
9  1 W
10 1 W

In this data frame we can see by inspection that there is a one-to-one correspondence between A and B (with 0 = H, 1 = W and 2 = M). I would like to find a way to do this for a larger data-frame using appropriate R code that does not require me to inspect each element. The code should produce a simple and clear statement of whether or not there is a one-to-one relationship between the specified variables; a simple TRUE/FALSE output should be ideal.

like image 256
Ben Avatar asked Dec 10 '22 05:12

Ben


1 Answers

If we want to check whether 'A', 'B' have duplicates, use duplicated from base R

i1 <- duplicated(DF)|duplicated(DF, fromLast = TRUE)

and wrap with all if we need a single TRUE/FALSE

all(i1)
#[1] TRUE

can be wrapped into a function

f1 <- function(dat) all(duplicated(dat)|duplicated(dat, fromLast = TRUE))
f1(DF)
#[1] TRUE
like image 144
akrun Avatar answered Jan 08 '23 06:01

akrun