Home > front end >  logical operator TRUE/FALSE in R
logical operator TRUE/FALSE in R

Time:09-27

I wrote a simple function that produces all combinations of the input (a vector). Here the input vector is basically a sequence of 4 coordinates (x, y) as mentioned inside the function as a, b,c, and d.

intervals<-function(x1,y1,x2,y2,x3,y3,x4,y4){
  a<-c(x1,y1)
  b<-c(x2,y2)
  c<-c(x3,y3)
  d<-c(x4,y4)
  union<-expand.grid(a,b,c,d)
union
  }

intervals(2,10,3,90,6,50,82,7)


> intervals(2,10,3,90,6,50,82,7)
   Var1 Var2 Var3 Var4
1     2    3    6   82
2    10    3    6   82
3     2   90    6   82
4    10   90    6   82
5     2    3   50   82
6    10    3   50   82
7     2   90   50   82
8    10   90   50   82
9     2    3    6    7
10   10    3    6    7
11    2   90    6    7
12   10   90    6    7
13    2    3   50    7
14   10    3   50    7
15    2   90   50    7
16   10   90   50    7
> 

Now I want to find (max of x) and (min of y) for each row of the given output. E.g. row 2: we have 4 values (10, 3, 6, 82). Here (3,6,82) are from x (x2,x3,x4) and 10 is basically from y (y1). Thus max of x is 82, and the min of y is 10.

So what I want is two values from each row.

I do not actually know how to approach this kind of logical command. Any idea or suggestions?

CodePudding user response:

You can pass x and y vector separately to the function. Use expand.grid to create all combinations of the vector and get max of x and min of y from each row.

intervals<-function(x, y){
  tmp <- do.call(expand.grid, rbind.data.frame(x, y))
  names(tmp) <- paste0('col', seq_along(tmp))
  result <- t(apply(tmp, 1, function(p) {
    suppressWarnings(c(max(p[p %in% x]), min(p[p %in% y])))
  }))
  result[is.infinite(result)] <- NA
  result <- as.data.frame(result)
  names(result) <- c('max_x', 'min_x')
  result
}

intervals(c(2,3,6,82), c(10, 90, 50, 7))

#   max_x min_x
#1     82    NA
#2     82    10
#3     82    90
#4     82    10
#5     82    50
#6     82    10
#7     82    50
#8     82    10
#9      6     7
#10     6     7
#11     6     7
#12     6     7
#13     3     7
#14     3     7
#15     2     7
#16    NA     7
  • Related