R函数计算不同时间点的值并绘制图形
我是R的初学者,希望得到专家的帮助。 我想创建一个函数来计算3种情况下的风险 第一个:控件:Xhh=0 Xmi=0 2st:hh:Xhh=1 Xmi=0 第三:hh+mi:Xhh=1 Xmi=1 比较两组之间的差异 第1组:Xenv=50 第2组:Xenv=90 我的参数:R函数计算不同时间点的值并绘制图形,r,loops,time,equation,curve,R,Loops,Time,Equation,Curve,我是R的初学者,希望得到专家的帮助。 我想创建一个函数来计算3种情况下的风险 第一个:控件:Xhh=0 Xmi=0 2st:hh:Xhh=1 Xmi=0 第三: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
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
我想把所有这些参数都加到这个方程中
并计算不同时间点的数值,
Ti=从1到10
对于Ti=0,将值设为0
然后用不同时间点的值绘制一张图,用这三种情况下的三条曲线进行比较。因此,在图的末尾有6条曲线
有人能提供一些帮助吗?这可能比你在这里得到的解释要多一些,但我正在寻找一个今天早上在其他任务上拖延的原因 我认为这符合您的需求,如下所述:
#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)
#定义一个名为myfunction的函数
myfunction您不需要循环。只需编写一个函数(即,您可以几乎一字不差地将公式复制到R中)。然后,该函数将接受时间向量作为输入。您可能还对curve
函数感兴趣。请阅读此文档:谢谢,@Roland。按照你的建议去掉了循环。学到了一些新东西!