[R] An iterative function

li li hannah.hlx at gmail.com
Mon Oct 30 03:24:06 CET 2017


Dear all,
  The function f() below is a function of m1 and m2, both of which are
matrices with 3 rows. The function works sequentially one row after
another.
So altogether there are three stages. I am trying to update the coding to
write a generic function that will work for arbitrary k stages.
  I am hoping to get some suggestion and help. Thanks so much!
         Hanna




 ##x, y are two vectors of the same length
f0 <- function(x, y){
  I <- which((x-y)^2>0.5)
  if (length(I)==0){
    a <- 0; b <-0; c<- 0
  } else {
  a <- min(I)
  b <- x[a]
  c <- y[a]}
  return(list(a=a, b=b, c=c))
}

##both m1 and m2 are matrix with 3 rows and same number of columns
f <- function(m1, m2){
  n <- dim(m1)[2]
  tmp1 <- f0(m1[1,], m2[1,])
  S2 <- which(m1[1,] > tmp1$a)
  if (length(S2) == 0){
    t1 <- c(tmp1$b, 0, 0)
    t2 <- c(tmp1$c, 0, 0)} else {
    tmp2 <- f0(m1[2,S2], m2[2, (n-length(S2)+1):n])
    S3 <- S2[which(m2[2, S2] > tmp2$a)]
    if (length(S3) == 0) {
      t1 <- c(tmp1$b, tmp2$b, 0)
      t2 <- c(tmp1$c, tmp2$c, 0)} else {
        tmp3 <- f0(m1[3,S3], m2[3,  (n-length(S3)+1):n])
        t1 <- c(tmp1$b, tmp2$b, tmp3$c)
        t2 <- c(tmp1$c, tmp2$c, tmp3$b)
      }}
  return(list(t1=t1, t2=t2))
}

	[[alternative HTML version deleted]]



More information about the R-help mailing list