r - Can I pass row elements as arguments with apply? How? -
starting sample data:
sample_data <- data.frame(id = 1:3, x = c(128, 113, 126), n = c(347, 344, 347), m = c(335, 334, 347), index = c(11, 9, -1)) theta <- matrix(c(0.5 ,0.5, 2, 2), nrow=2, ncol=2) lhs <- function(a, b, g, d, dat){ beta(a + dat$x, b + dat$n - dat$x) / beta(a, b) * beta(g, d + dat$n) / beta(g, d) }
the function lhs returns vector of same number of rows argument dat.
rhs <- function(dat, ...){ n = dat$n m = dat$m x = dat$x index = dat$x temp <- data.frame(i = 0:index, n = rep(n, index + 1) , m = rep(m, index + 1) , x = rep(x, index + 1)) sum(beta(a + temp$x, b + temp$m - temp$x + temp$i) / beta(a,b) * beta(g + 1, d + temp$m + temp$i) / beta(g, d)) }
the function rhs works on single row because each observation has different value index (the index sum inside rhs). intent return 1 value per row in dat. i've tried apply in function ll (below).
ll <- function(theta, dat){ <- theta[1,1] b <- theta[2,1] g <- theta[1,2] d <- theta[2,2] .lhs <- lhs(a, b, g, d, dat) .rhs <- ifelse(index > -1, apply(dat, 1, rhs), 0) sum(log(.lhs+log.rhs)) }
it seems need able pass value of index, n, m, , x rhs given row. is, not vector of length(data$n), value of n @ row being passed through apply in function ll.
is correct approach? how can such thing?
thanks.
edit
i've clean things bit , made slight modification sample data. correct return value -i think! - can arrived @ (explicitly passing a,b,g, , d)
sum(lhs(a = theta[1,1], b = theta[2,1], g = theta[1,2], d = theta[2,2], sample_data)) + rhs(sample_data[1,]) + rhs(sample_data[2,]) + rhs(sample_data[3,])
Comments
Post a Comment