[R] repeat rows of matrix by number (k) in one colummatrix adding column j with values 1:k

Rasmus Liland jen@r@@mu@ @end|ng |rom gm@||@com
Thu Apr 2 22:04:47 CEST 2020


On 2020-04-01 15:33 +1100, Jim Lemon wrote:
> Hi Nevil,
> It's a nasty piece of work, but:

Hi!  How about this one:

    data <- c(rep(1:4, times=3), 2, 1, 3, 2)
    dimnames <- list(NULL, c("x", "y", "z", "k"))
    ncol <- length(data)/4
    M <- matrix(data=data, nrow=ncol, ncol=ncol, dimnames=dimnames)
    
    FUN <- function(x) {
      out <- matrix(rep(x[1:3], times=x[4]),
                    byrow=TRUE, nrow=x[4])
      return(cbind(out, x[4]))
    }
    newM <- do.call(rbind, apply(X=M, MARGIN=1, FUN=FUN))
    dimnames(newM) <- list(NULL, c("x", "y", "z", "k"))
    newM <- cbind(newM, "j"=sequence(M[,"k"]))
    newM

Regards,
Rasmus



More information about the R-help mailing list