[R] How to select one value per row (different columns) from array

William Michels wjm1 at caa.columbia.edu
Wed Mar 1 15:38:15 CET 2017


Hello Wolfgang,

Building on Peter Dalgaard's code, are you just trying to take a sample of
a random column from each row? You don't need to use apply:

> array[cbind(1:nrow(array), sample.int(ncol(array), nrow(array),
replace=TRUE ))]

Just a general note, since you're sampling one-column-per-row from an array
with more rows than columns, you'll have to set replace=TRUE. However,
there may be other datasets where you have more columns than rows and never
want to sample each column more than once, in which case you would set
replace=FALSE.

Best Regards.



On Wed, Mar 1, 2017 at 5:38 AM, peter dalgaard <pdalgd at gmail.com> wrote:

>
> array[cbind(1:999,vector)]
>
> -pd
>
> On 01 Mar 2017, at 14:28 , Wolfgang Waser <waser at frankenfoerder-fg.de>
> wrote:
>
> > Dear all,
> >
> > I have to pick one value per row from an array, but from row to row from
> > a different column. The column positions of the values for each row are
> > stored in a vector.
> >
> > array: 999 rows, 48 columns
> >
> > vector: 999 values (each between 1 and 48) indicating for each row which
> > value to pick from that row.
> >
> > Is there a non-loop way to pick the 999 values from the array, probably
> > using some form of ?apply?
> >
> >
> > Thank you very much for help and suggestions!
> >
> > Wolfgang
> >
> > ______________________________________________
> > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide http://www.R-project.org/
> posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
>
> --
> Peter Dalgaard, Professor,
> Center for Statistics, Copenhagen Business School
> Solbjerg Plads 3, 2000 Frederiksberg, Denmark
> Phone: (+45)38153501
> Office: A 4.23
> Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/
> posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list