Here's one way:

y/outer(rep(1, nrow(y)), x)
     [,1] [,2]     [,3] [,4] [,5]
[1,]    1  3.5 4.333333 4.75  5.0
[2,]    2  4.0 4.666667 5.00  5.2
[3,]    3  4.5 5.000000 5.25  5.4
[4,]    4  5.0 5.333333 5.50  5.6
[5,]    5  5.5 5.666667 5.75  5.8
[6,]    6  6.0 6.000000 6.00  6.0

Run the outer command by itself to see what it does.

HTH,
Dennis

On Thu, Jan 27, 2011 at 7:18 AM, adam_pgsql <adam_pgsql@witneyweb.org>wrote:

>
> Hi,
>
> I'd like to divide each element of a matrix by a specific value per column.
> These specific values are stored in a list. For example:
>
> > x <- c(1,2,3,4,5)
> > y <- matrix(c(1:30), nrow = 6)
>
> Now I want to divide each element in y[,1] by x[1], y[,2] by x[2] etc. I
> have tried this
>
> > my_function <- function(data, ind) data/ind
> > apply(y, 2, my_function, x)
>     [,1] [,2] [,3] [,4] [,5]
> [1,]    1  7.0 13.0 19.0 25.0
> [2,]    1  4.0  7.0 10.0 13.0
> [3,]    1  3.0  5.0  7.0  9.0
> [4,]    1  2.5  4.0  5.5  7.0
> [5,]    1  2.2  3.4  4.6  5.8
> [6,]    6 12.0 18.0 24.0 30.0
> Warning messages:
> 1: In data/ind :
>  longer object length is not a multiple of shorter object length
> 2: In data/ind :
>  longer object length is not a multiple of shorter object length
> 3: In data/ind :
>  longer object length is not a multiple of shorter object length
> 4: In data/ind :
>  longer object length is not a multiple of shorter object length
> 5: In data/ind :
>  longer object length is not a multiple of shorter object length
>
> but as you can see it is applying them by row rather than column. Any ideas
> how to do this? Is there a variable within 'apply' that can be used to
> determine which column of y is being processed?
>
> thanks for any help
>
> adam
>
> > sessionInfo()
> R version 2.11.1 (2010-05-31)
> x86_64-apple-darwin9.8.0
>
> locale:
> [1] en_GB.UTF-8/en_GB.UTF-8/C/C/en_GB.UTF-8/en_GB.UTF-8
>
> attached base packages:
> [1] stats     graphics  grDevices utils     datasets  methods   base
>
> ______________________________________________
> R-help@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.
>

	[[alternative HTML version deleted]]

