[R] repeat rows of matrix by number (k) in one colummatrix adding column j with values 1:k
Jim Lemon
drj|m|emon @end|ng |rom gm@||@com
Thu Apr 2 22:39:29 CEST 2020
Hi Rasmus,
Very nice. The R help list is a bit like a quiz show where the
contestants must balance the alacrity with which they press their
buttons with the confidence that they have the correct answer. A slow
motion game of wits in which the prizes are self-awarded.
Jim
On Fri, Apr 3, 2020 at 7:04 AM Rasmus Liland <jensrasmus using gmail.com> wrote:
>
> 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