[R] matrix question

Rolf Turner r.turner at auckland.ac.nz
Wed Aug 20 00:43:32 CEST 2008


On 20/08/2008, at 10:08 AM, Altaweel, Mark R. wrote:

> Hi,
>
> I have a vector and a list, with data I would like to multiply  
> together.

	No you haven't.  You have two ***lists***.  Lists and vectors
	are not the same thing.  If you don't distinguish between them
	you will confuse everyone, including yourself.
>
> So for instance I have a vector s:
>
> [[1]]
> [1] 44308
>
> [[2]]
> [1] 4371
>
> Also, I have a list d:
>
> [[1]]
>  [1] 1201 6170 2036 2927 1625 1391 2074 1453 3172 3027 4691 3719  
> 1185  320 2071 1027 1046 1186 1403  580 1382  440    8  174
>
> [[2]]
>  [1] 6521  688 2678 3409 3033 1608 3618 1461 1836 2104  879 1095  
> 2630 1591 2986  703 2548  913 1426  753  256  869  106
>
>
> I want to multiply them together and put the results in a matrix.
>
> This is my syntax:
>
> for(i in 1:length(s))
>  for(j in 1:length(d))
>    m<-d[[j]][j]/s[[i]]  #m is the matrix of dimensions set to X 
> (e.g. 10X10)
>
> However, it seems I only get one result when i get m, which is the  
> last value of d/j, which is m[1]=0.04 in this case.
>
> I am sure Im doing something wrong here, but can't quite find the  
> solution.

	The object m has been repeatedly assigned the value ``d[[j]][j]/s 
[[i]]'' and
	so naturally ends up having the last value that it was assigned.

	If you want m to be a matrix, make it one, and assign values to its  
entries!
	
	m <- matrix(NA,length(s),length(d))

	for(i in 1:length(s)) {
		for(j in 1:length(d)) {
			m[i,j] <-d[[j]][j]/s[[i]]
		}
	}

It's not at all clear if the foregoing is really what you are  
intending to do, since it's
not at all clear what you are intending to do.  Did you really want  
``d[[j]][j]'' (i.e. 2 j-s)???
Are you aware that the two entries of d are of different lengths (24  
and 23 respectively) and
that you only use the first entry of the first and the second entry  
of the second.  Why are you
using lists rather than vectors and matrices?

You could achieve the same result as the convoluted shaganappi  
foregoing code by doing

	
	u <- matrix(c(1201,688),2,2,byrow=TRUE)
	v <- c(44308,4371)
	m <- u/v

But as I indicated, that's probably not what you really want to do.   
You need to get
your thoughts organized.

	cheers,

		Rolf Turner

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}



More information about the R-help mailing list