[R] Question

Bill.Venables@cmis.csiro.au Bill.Venables at cmis.csiro.au
Tue May 14 14:28:28 CEST 2002


Hi Alessandro,

>  -----Original Message-----
> From: 	Ambrosini Alessandro [mailto:klavan at tiscalinet.it] 
> Sent:	Tuesday, May 14, 2002 10:14 PM
> To:	R-help
> Subject:	[R] Question
> 
> Hello. I want to use "for".
	[WNV]  Are you sure?  

> I have a matrix called "mat" that has got 100 rows.
> I want to take the line 1 and make
> 
> a1<-which(mat[1,]==1)
> 
> After this I want to take the second row and make
> 
> a2<-which(mat[2,]==1)
> 
> and so on until I arrive at row 100.
> 
> I want to make it automatic for the 100 rows and so I wrote:
> 
> for(i in 1:nrow(mat)){
>        ai<-which(mat[i,]==1) 
>  }
> 
> but it doesn't work.
> I need to obtain 100 vectors called a1,a2,a3,...,a100. 
	[WNV]  Do you really want 100 separate objects?  Would a list of 100
answers do?

	Here is one way to make a list with the vectors you want

		aList <- apply(mat, 1, function(x) which(x == 1))

	Then aList[[i]] is what you would call ai

	If you really do want 100 separate objects you can do that as a
further step

		for(i in 1:100) assign(paste("a", i, sep=""), aList[[i]])

	but that seems an awkward thing to do to me.

	<begin sermon>
	S (respectively R) encourages you to take the "whole object" view of
a calculation.  An extension of that is to take the "whole problem" view in
asking for help.  Rather than form a fixed view on how a problem is to be
solved it is better to present the whole problem to see if someone has an
elegant strategy for the whole thing you may not have anticipated.  Now that
you have the 100 objects, what are you going to do with them, for example.
I know there are ways in SAS, SPSS and even Genstat for dealing with
specially named objects in sequence, but such devices are a bit more complex
in S (resp R) and simpler methods are available.

	<end sermon>

> Please help me.
> Alessandro
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
> -.-.-
> r-help mailing list -- Read
> http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._.
> _._._
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list