[R] how to divide each element of a matrix by a specific value per column
adam_pgsql
adam_pgsql at witneyweb.org
Thu Jan 27 16:18:15 CET 2011
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
More information about the R-help
mailing list