-1

I have two people coding the same variables for a psychological test (more than 400 variables), and I need to compare the datasets. I need two results:

  1. I need to see only the specific cases with mismatch and
  2. As the final result, I need the percentage of mismatch per variable.

here what I mean by the "percentage of mismatch per variable":

A <- tibble( ID = c(1:10),  
         v1 = rep(1),
         v2 = rep(2), 
         v3 = rep(3))


B <- tibble( ID = c(1:10),  
             v1 = c(1,1,1,1,10,1,1,1,1,1),
             v2 = c(30,2,2,2,51,2,2,2,2,40), 
             v3 = c(3,3,3,3,3,3,3,65,3,90))

A;B

# A tibble: 10 x 4
      ID    v1    v2    v3
   <int> <dbl> <dbl> <dbl>
 1     1     1     2     3
 2     2     1     2     3
 3     3     1     2     3
 4     4     1     2     3
 5     5     1     2     3
 6     6     1     2     3
 7     7     1     2     3
 8     8     1     2     3
 9     9     1     2     3
10    10     1     2     3
# A tibble: 10 x 4
      ID    v1    v2    v3
   <int> <dbl> <dbl> <dbl>
 1     1     1    30     3
 2     2     1     2     3
 3     3     1     2     3
 4     4     1     2     3
 5     5    10    51     3
 6     6     1     2     3
 7     7     1     2     3
 8     8     1     2    65
 9     9     1     2     3
10    10     1    40    90

How do I compare dataset A with dataset B to get a result like this:

result<- tibble(variables = c("v1", "v2", "v3"),
                 n.mismatch = c(1,3,2),
                 percentage.mismatch = c(0.10, 0.30, 0.20))
result
# A tibble: 3 x 3
  variables n.mismatch percentage.mismatch
  <chr>          <dbl>               <dbl>
1 v1                 1                 0.1
2 v2                 3                 0.3
3 v3                 2                 0.2
Caleb Bassham
  • 1,874
  • 2
  • 16
  • 33
Ruam Pimentel
  • 1,288
  • 4
  • 16

1 Answers1

1

We can use Map to compare the column values.

as.data.frame(Map(function(x, y) {
   inds <- x != y
   c(n.mismatch = sum(inds), percentage.mismatch = mean(inds))
}, A[-1], B[-1]))

#                    v1  v2  v3
#n.mismatch          1.0 3.0 2.0
#percentage.mismatch 0.1 0.3 0.2

Similarly, in tidyverse, we can use map2

purrr::map2_df(A[-1], B[-1], ~{
   inds = .x != .y
   tibble::tibble(n.mismatch = sum(inds), percentage.mismatch = mean(inds))
 }, .id = "variables")

#  variables n.mismatch percentage.mismatch
#  <chr>          <int>               <dbl>
#1 v1                 1                 0.1
#2 v2                 3                 0.3
#3 v3                 2                 0.2
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213