[R] sapply or apply
Joshua Wiley
jwiley.psych at gmail.com
Thu Jun 17 08:30:40 CEST 2010
Hello Roslina,
Maybe it is just me, but I have difficulty picking apart what you are
trying to do because, the data have the same names as the arguments in
your functions, and when you create the function term(), you have two
sets of arguments (for term() and for gam_sum() ) that have the same
names in addition to data with the same names. You also rely on the
arguments' locations rather than explicitly stating their names. My
guess is that you are having problems because sapply() is passing data
from 'bt' to the first argument of gam_sum(), (which is named 'alp' ),
so you *might* not be using the data you think you are in the
arguments you think you are.
At any rate, I can tell you what is happening right now with term().
It is calling gam_sum() for each individual element of 'bt' like so:
gam_sum(bt[1],alp,bt_min,1)
gam_sum(bt[2],alp,bt_min,1)
gam_sum(bt[3],alp,bt_min,1)
gam_sum(bt[4],alp,bt_min,1)
and taking the sum of all of these. Note that since the data 'alp'
has 4 elements, gam_sum() also puts out 4 elements, for each element
of the data 'bt' .
Best regards,
Josh
On Wed, Jun 16, 2010 at 5:21 PM, Roslina Zakaria <zroslina at yahoo.com> wrote:
> Hi r-users,
>
> I have this code here :
>
> dt <- winter_pos_sum
> bt <- c(24.96874, 19.67861, 23.51001, 19.86868); round(bt,2)
>
> alp <- c(2.724234, 3.914649, 3.229146, 3.120719); round(alp,2)
>
> bt_min <- min(bt) ; bt_min
> p <- alp_sum ; p
> t <- 50
> t1 <- t+1
>
>
> #first get the sum over the eigenvalues for a particular power i
> gam_sum <- function(alp,bt,bt_min,i) {alp*(1-bt_min/bt)^i}
> gam_sum(alp,bt,bt_min,1)
> 0.57718379+ 0.00000000+ 0.52625031+ 0.02985377 = 1.133288
>
>
>
> term <- function(i,alp,bt,bt_min) {sum(sapply(bt,gam_sum , alp,bt_min,i))}
>> term (1,alp,bt,bt_min)
> [1] -1817.765
>
>
> I should get the value using term (1,alp,bt,bt_min)=1.133288. I have 4 values of beta and 4 values of alpha.
>
> Thank you so much for your help.
>
>
>
> [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at 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.
>
>
--
Joshua Wiley
Ph.D. Student
Health Psychology
University of California, Los Angeles
More information about the R-help
mailing list