Reputation: 186
Suppose I have the following Dataframe (reproducible example follows):
DF <- data.frame(ID=c(12345,12345,13425),NumTrans=c("1-2","2-3","1-3"),Cov1=c(1500,1000,2000),cov2=c(1,0,1))
The field NumTrans represents transitions between states: subject 12345, say, transitions between states 1 and 2, and so on. Writing the function "func" as follows,
func=function(x){
a=paste0("exp(",x[1],"*x","+",x[2],"*y)")
return(a)
}
allows you to associate to each ID an expression outputting exp(Cov1*x1 + Cov2*y):
by(DF[3:4],DF[1],func)
ID: 12345
[1] "exp(c(1500, 1000)*x+c(1, 0)*y)"
-----------------------------------------
ID: 13425
[1] "exp(2000*x+1*y)"
However, what I need is slightly different.
1) Is there any way to modify this function such that on the "*x" and "*y" you obtain instead "*x_NumTrans" and "*y_NumTrans", where NumTrans is the NumTrans of that row?
2) Is it possible to write a function that returns this output, but equal to the number of rows?
In other words, the desired output is something like:
[1] "exp(c(1500, 1000)*x_1-2+c(1, 0)*y_1-2)"
----------------------------------------------
[2] "exp(c(1500, 1000)*x_2-3+c(1, 0)*y_2-3)"
----------------------------------------------
[3] "exp(2000*x_1-3+1*y_1-3)"
----------------------------------------------
Or even better, a solution that puts each of these expressions in a column that can be appended to DF...
Many thanks in advance!
Upvotes: 0
Views: 42
Reputation: 25225
You can do it as follows. Split into 2 sections. The first for those with c(*,*)
and then paste the results with NumTrans
byAns <- by(DF[2:4], DF[1], function(x) {
s1 <- paste0("exp(", x[2], "*x_")
s2 <- paste0("+", x[3], "*y_")
paste0(s1, x[[1]], s2, x[[1]], ")")
})
Upvotes: 1