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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With