我是R的初学者,希望得到专家的帮助。 我想创建一个函数来计算3个条件下的风险
1st:control:Xhh = 0 Xmi = 0
2st:hh:Xhh = 1 Xmi = 0
第3:hh + mi:Xhh = 1 Xmi = 1
并比较两组
组1:Xenv = 50
第2组:Xenv = 90
我的参数:
thi lambda1 lambda2 lambda3 Beta Z2 Z1 Z4 Z3 Z6 Z5 theta
1.38 0.34 0.25 0.49 0.5 0.58 0.55 0.59 0.56 0.44 0.61 0.88
我想将所有这些参数插入此等式中 http://i.stack.imgur.com/DYR81.png
并计算不同时间点的值, Ti = 1至10
对于Ti = 0,将值设为0
然后用不同时间点的值绘制图形,用这三个条件的3条曲线进行比较,并在两组之间进行比较。所以最后在图中有6条曲线。
有人可以提供一些帮助吗?
答案 0 :(得分:1)
这可能是对你的需求的一点解释,而不是你倾向于到达这里,但我正在寻找一个拖延今天早上其他任务的理由。
我认为这符合您的要求:
#define a function called myfunction
myfunction <- function(lambda1 = 0.34
,lambda2 = 0.25
,lambda3 = 0.49
,Beta = 0.5
,Z2 = 0.58
,Z1 = 0.55
,Z4 = 0.59
,Z3 = 0.56
,Z6 = 0.44
,Z5 = 0.61
,theta = 0.88
,Xenv
,Xhi
,Xmi
,Tmin
,Tmax){
#this should make this function somewhat generalizable to values of T
#create an empty vector to hold values of our function as defined
f <- rep(NA, length(Tmin:Tmax))
#loop through values of T in your function
#check parentheses here - I make no promises
#I'm also unclear what your value of thi is. I may be missing something,
#but I don't see it in the function you have written
i <- Tmin:Tmax
f <- -log(exp((-(lambda1*i)^theta)*exp(log10(1-Beta*Xhi)+log10((Xenv/100)*(Z2-Z1)+Z2))-
((lambda2*i)^theta)*exp(log10(1-Beta*Xmi))*log10((Xenv/100)*(Z4-Z3)+Z4)-
((lambda3*i)^theta)*exp(log10((Xenv/100)*(Z6-Z5)+Z6)))*(1-theta)+theta)
#set f=0 at T=0 (I think this is what you want)
if(Tmin==0) f[1] <- 0
return(f)
}
#you didn't specify how to plot, but this seems to lend itself to a ggplot facted viz.
require(ggplot2)
require(reshape2)
#calculate for group 1
datg1 <- data.frame(t = 0:10
,group = 1
,condition1 = myfunction(Xenv=50, Xhi=0, Xmi=0, Tmin=0, Tmax=10)
,condition2 = myfunction(Xenv=50, Xhi=1, Xmi=0, Tmin=0, Tmax=10)
,condition3 = myfunction(Xenv=50, Xhi=1, Xmi=1, Tmin=0, Tmax=10)
)
#calculate for group 2
datg2 <- data.frame(t = 0:10
,group = 2
,condition1 = myfunction(Xenv=90, Xhi=0, Xmi=0, Tmin=0, Tmax=10)
,condition2 = myfunction(Xenv=90, Xhi=1, Xmi=0, Tmin=0, Tmax=10)
,condition3 = myfunction(Xenv=90, Xhi=1, Xmi=1, Tmin=0, Tmax=10)
)
#bind values together
dat <- rbind(datg1, datg2)
#melt your data into long format
datm <- melt(dat, id.vars = c("t", "group"))
#plot and facet
ggplot(datm, aes(x=t, y=value, colour=variable)) +
geom_line() +
facet_grid(.~group)