[R] sampling rows from a list
Justin Haynes
jtor14 at gmail.com
Mon Apr 2 22:30:56 CEST 2012
## recreating your data
mydata<-list(matrix(1:9, nrow=3, byrow=T),
matrix(10:15, nrow=2, byrow=T),
matrix(16:30, nrow=5, byrow=T))
## get the shortest matrix in your list
n <- min(unlist(lapply(mydata, nrow)))
## subset the list into random samples of length n
out <- lapply(mydata, function(x, n) x[sample(1:nrow(x), n),], n=n)
## this structure is still a list though...
## converting directly to an array:
out.array <- array(unlist(out), dim=c(dim(out[[1]]), length(out)))
not totally sure about what structure you're wanting in the last step,
so if i missed i apologize...
Hope that helps,
Justin
On Mon, Apr 2, 2012 at 11:24 AM, Bcampbell99 <BrianD.Campbell at ec.gc.ca> wrote:
> Hi:
>
> I'm sure this seems like a rudimentary question, but I am not well versed
> with R syntax for lists. I have a ragged array from which I've removed
> records (entire rows) with missing data. The functions I used to remove the
> missing cases resulted in the generation of an R list class object, that
> looks something like this;
>
> mydata
> [[1]]
> [,1] [,2] [,3]
> [1,] 1 2 3
> [2,] 4 5 6
> [3,] 7 8 9
>
> [[2]]
> [,1] [,2] [,3]
> [1,] 10 11 12
> [2,] 13 14 15
>
> [[3]]
> [,1] [,2] [,3]
> [1,] 16 17 18
> [2,] 19 20 21
> [3,] 22 23 24
> [4,] 25 26 27
> [5,] 28 29 30
>
> Part1
> What I would like to do is draw an equal number of random row samples
> from[[1]],[[2]] and [[3]] (to preserve the structure of [,1][,2],[,3].
>
> Part2
> Then I would like to cocerce the list object into something like an array.
>
> Help scripting out part 1 or 2 would be much appreciated.
>
> Brian Campbell
>
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/sampling-rows-from-a-list-tp4526831p4526831.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
More information about the R-help
mailing list