From i@uc@r86 @ending from gm@il@com  Fri Jun  8 19:07:16 2018
From: i@uc@r86 @ending from gm@il@com (=?UTF-8?B?ScOxYWtpIMOaY2Fy?=)
Date: Fri, 8 Jun 2018 19:07:16 +0200
Subject: [Rd] Subsetting the "ROW"s of an object
In-Reply-To: <CABdHhvF9R3Mpk9pMMy8wa=qXzGta9cXdb9BYKT4P69QRuU3rig@mail.gmail.com>
References: <CABdHhvF9R3Mpk9pMMy8wa=qXzGta9cXdb9BYKT4P69QRuU3rig@mail.gmail.com>
Message-ID: <CALEXWq2pZRYDBzbBV=_qfamDm0r+t=SVLizjd24t2CsWgUUjvw@mail.gmail.com>

El vie., 8 jun. 2018 a las 17:46, Hadley Wickham
(<h.wickham at gmail.com>) escribi?:
>
> Hi all,
>
> Is there a better to way to subset the ROWs (in the sense of NROW) of
> an vector, matrix, data frame or array than this?
>
> subset_ROW <- function(x, i) {
>   nd <- length(dim(x))
>   if (nd <= 1L) {
>     x[i]
>   } else {
>     dims <- rep(list(quote(expr = )), nd - 1L)
>     do.call(`[`, c(list(quote(x), quote(i)), dims, list(drop = FALSE)))
>   }
> }
>
> subset_ROW(1:10, 4:6)
> #> [1] 4 5 6
>
> str(subset_ROW(array(1:10, c(10)), 2:4))
> #>  int [1:3(1d)] 2 3 4
> str(subset_ROW(array(1:10, c(10, 1)), 2:4))
> #>  int [1:3, 1] 2 3 4
> str(subset_ROW(array(1:10, c(5, 2)), 2:4))
> #>  int [1:3, 1:2] 2 3 4 7 8 9
> str(subset_ROW(array(1:10, c(10, 1, 1)), 2:4))
> #>  int [1:3, 1, 1] 2 3 4
>
> subset_ROW(data.frame(x = 1:10, y = 10:1), 2:4)
> #>   x y
> #> 2 2 9
> #> 3 3 8
> #> 4 4 7
>
> It seems like there should be a way to do this that doesn't require
> generating a call with missing arguments, but I can't think of it.

The following code seems to work. The only minor drawback is that, for
the last case, the output is not a data frame.

subset_ROW <- function(x, i) {
  nd <- length(dim(x))
  if (nd <= 1L)
    return(x[i])
  xx <- apply(x, 2:nd, `[`, i, drop=FALSE)
  dim(xx) <- c(length(i), dim(x)[-1])
  xx
}

I?aki

>
> Thanks!
>
> Hadley
>
> --
> http://hadley.nz
>



[Rd] Subsetting the "ROW"s of an object
=?UTF-8?B?ScOxYWtpIMOaY2Fy?=