Home > Mobile >  In R, How to make a function that finds if there is a matching pairs?
In R, How to make a function that finds if there is a matching pairs?

Time:04-27

I want to make a function that can detect if there is a matching pair of numbers. I want to simulate x and y many times to see the # of matches occurring using a function.

x<-sample(1:6,6)
y<-sample(1:6,6)
x;y

For example, I have x<- c(2, 5, 6, 4, 3, 1)and y<- c(2, 1, 6, 5, 4, 3). Numbers 2 and 6 matches in order. There are 2 pairs. If there is no match between x and y, it should be just 0. I can use sum(x==y) to find for one example of x and y.

How can I make a function that finds number of identical pairs for many x and y?

CodePudding user response:

You can just use

f<-function(n,k) {
  sapply(1:k, \(i) sum(sample(n) == sample(n)))
}

where k is the number of iterations and n is the range (in your case 6)

Example Usage:

f(n=6, k=100)

CodePudding user response:

In base R the following function would do the trick. The length of vector is given by the size argument, and the number of trials is given by n

n_pairs <- function(size, n) {
  colSums(replicate(n, sample(size)) == replicate(n, sample(size)))
}

So, for example we can see:

set.seed(1)

n_pairs(size = 6, n = 5)
#> [1] 2 0 1 1 1

hist(n_pairs(6, 100), breaks = 0:6)

mean(n_pairs(6, 1000))
#> [1] 1.013

Note though that R already has the function rbinom, which can achieve the same result with:

rbinom(n, size, 1/size)

Created on 2022-04-26 by the reprex package (v2.0.1)

CodePudding user response:

Maybe this one (removed first answer):

x<- c(2, 5, 6, 4, 3, 1) 
y<- c(2, 1, 6, 5, 4, 3)

lst = list(x,y)

pairs <- outer(lst,lst,Vectorize(function(x,y){x[x==y]}))

pairs[1,2]
[[1]]
[1] 2 6

CodePudding user response:

A possible solution with dplyr package

 require(tidyverse)

x <- c(2, 5, 6, 4, 3, 1)
y <- c(2, 1, 6, 5, 4, 3)

df <- tibble(x = x,
             y = y) %>%
  mutate(pair = case_when(x == y ~ "PAIR",
                          TRUE ~ "NOT"))

The dataset:

# A tibble: 6 x 3
      x     y pair 
  <dbl> <dbl> <chr>
1     2     2 PAIR 
2     5     1 NOT  
3     6     6 PAIR 
4     4     5 NOT  
5     3     4 NOT  
6     1     3 NOT  

Filtering:

df %>%  
  filter(pair == "PAIR")

Output:

# A tibble: 2 x 3
      x     y pair 
  <dbl> <dbl> <chr>
1     2     2 PAIR 
2     6     6 PAIR 

CodePudding user response:

Will this give you what you want? Make a table out of the values that are paired.

table(x[x==y])
x <- sample(1:6,1000, TRUE)
y <- sample(1:6,1000, TRUE)
  
table(x[x==y])
#  1  2  3  4  5  6 
# 37 26 32 28 30 33 
  •  Tags:  
  • r
  • Related