Skip to content

Copying rows from a matrix using a vector of indices

3 messages · Martin Lam, Marc Schwartz (via MN), Spencer Graves

#
Hi,

I am trying to use a vector of indices to select some
rows from a matrix. But before I can do that I somehow
need to convert 'combinations' into a list, since
'mode(combinations)' says it's 'numerical'. Any idea
how I can do that?

library("combinat")

combinations <- t(combn(8,2))

indices <- c(sample(1:length(combinations),10))

# convert
???

subset <- combinations[indices]

Thanks in advance,

Martin
#
On Wed, 2005-08-17 at 12:02 -0700, Martin Lam wrote:
Your goal is not entirely clear.  Given your code above, you end up
with:
[,1] [,2]
 [1,]    1    2
 [2,]    1    3
 [3,]    1    4
 [4,]    1    5
 [5,]    1    6
 [6,]    1    7
 [7,]    1    8
 [8,]    2    3
 [9,]    2    4
[10,]    2    5
[11,]    2    6
[12,]    2    7
[13,]    2    8
[14,]    3    4
[15,]    3    5
[16,]    3    6
[17,]    3    7
[18,]    3    8
[19,]    4    5
[20,]    4    6
[21,]    4    7
[22,]    4    8
[23,]    5    6
[24,]    5    7
[25,]    5    8
[26,]    6    7
[27,]    6    8
[28,]    7    8

combinations is a 28 x 2 matrix (or a 1d vector of length 56).

Your use of sample() with '1:length(combinations)' is the same as 1:56.
[1] 56

Hence, you end up with:
[1] 41 53 38 46 50 44 25 11 43  7


I suspect that you really want to use '1:nrow(combinations)', which
yields 1:28.
[1] 28


Thus,
[1] 21 26 18 22 23 20 11  5 27  3


Now, you can use:
[,1] [,2]
 [1,]    4    7
 [2,]    6    7
 [3,]    3    8
 [4,]    4    8
 [5,]    5    6
 [6,]    4    6
 [7,]    2    6
 [8,]    1    6
 [9,]    6    8
[10,]    1    4

which yields the rows from combinations, defined by 'indices'.

If correct, please review "An Introduction to R" and ?"[" for more
information on subsetting objects in R.

HTH,

Marc Schwartz
6 days later
#
I don't quite understand what you are asking.  Have you checked the 
sections on "Simple manipulations numbers and vectors", "Arrays and 
matrices", and "Lists and data frames" in the manual "An Introduction to 
R"?  If you still would like some help after this, PLEASE do read the 
posting guide! "http://www.R-project.org/posting-guide.html".  It can 
increase the chances that you will get a useful reply.

	  spencer graves
Martin Lam wrote: