nested - How to use parameters from data frame in R and loop through time holding them constant -


i have function (weisurv) has 2 parameters - sc , shp. function through time (t). time sequence, i.e. t<-seq(1:100).

weisurv<-function(t,sc,shp){ surv<-exp(-(t/sc)^shp) return(surv) } 

i have data frame (df) contains list of sc , shp values (like 300+ of them). example, have:

     m       shp     sc      p  c 1    1  1.138131 10.592154 0.1  1 1 2 1.01  1.143798 10.313217 0.1  1 2 3 1.02  1.160653 10.207863 0.1  1 3 4 1.03  1.185886  9.861997 0.1  1 4 ... 

i want apply each set (row) of sc , shp parameters function. function weisurv(t,sc[[i]],shp[i]]) each row[i]. not understand how use apply or adply though i'm sure 1 of these or combo of both needed. in end, looking data frame gives value of weisurv each time given set of sc , shp (held constant through time). if had 10 sets of sc , shp parameters, end 10 time series of weisurv. thanks....

using plyr:

as matrix (time in cols, rows corresponding rows of df):

aaply(df, 1, function(x) weisurv(t, x$sc, x$shp), .expand = false) 

as list:

alply(df, 1, function(x) weisurv(t, x$sc, x$shp)) 

as data frame (structure per matrix above):

adply(df, 1, function(x) setnames(weisurv(t, x$sc, x$shp), t)) 

as long data frame (one row per t/sc/shp combination); note uses mutate , pipe operator dplyr):

newdf <- data.frame(t = rep(t, nrow(df)), sc = df$sc, shp = df$shp) %>%   mutate(surv = weisurv(t, sc, shp)) 

you can create wide data.frame , use reshape2::melt reformat long:

widedf <- adply(df, 1, function(x) setnames(weisurv(t, x$sc, x$shp), t)) newdf <- melt(widedf, id.vars = colnames(df), variable.name = "t", value.name = "surv") newdf$t <- as.numeric(as.character(newdf$t)) 

pretty plot of last newdf (using ggplot2):

ggplot(newdf, aes(x = t, y = surv, col = sprintf("sc = %0.3f, shp = %0.3f", sc, shp))) + geom_line() + scale_color_discrete(name = "parameters") 

ggplot image of weisurv output


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -