MJH
MJH

Reputation: 398

add columns to data.frame from function

I am in the process of building a function for drug efficacy that depends both on age of administration and years since administration. The idea is to figure out the efficacy of a drug at the time you get it and then the decrease in efficacy as time goes on; for example, get drug at age 50, and then follow each year and see how efficacy changes. A modified version of the function is below.

What I would like to have at the end of this is a data.frame for drug efficacy with each column being the age at which the drug was administered (e.g., 50, 51, 52, ... , 85) and each row being the efficacy at each year after dosage (e.g., 1, 2, ... , 10).

I have tried a variety of things but have gotten basically nowhere. This code below is the closest I have got, but is still way off. If need be, the function can be restructured to two parts if that's easier.

Also if there is an easy way to name the columns that would be great, but that's the least of my concerns right now.

Any help would be greatly appreciated. Thank you

b2 <- 0.28
a1 <- 0.02
a2 <- 0.04
e  <- exp(1)

p_tot   <- 19132 + 18827 + 14505 
p1   <- 19132 
p2   <- 18827 
p3   <- 14505 

years_i <- seq(1, 10, by = 1)
age_j   <- seq(50, 85, by = 1)

VEij <- function(age_j, years_i){
  b1j <-   ((a1 - a2*age_j)*p_tot + b2*(p1 + 2*p2 + 3*p3)) / p_tot
  Efficacy <- b1j - b2*years_i
  return(Efficacy)
}

EffDF <- data.frame(years_i)

for (x in age_j){
  for (y in years_i){
    EffDF <- cbind(EffDF, VEij(x, y))
  }
}

Upvotes: 0

Views: 80

Answers (1)

Ricky
Ricky

Reputation: 4686

I am guessing this is what you want.

EffDF <- data.frame(sapply(as.list(age_j), VEij, years_i)
names(EffDF) <- age_j

Truncated output:

> EffDF
          50        51        52        53        54        55        56        57
1  -1.724694 -1.764694 -1.804694 -1.844694 -1.884694 -1.924694 -1.964694 -2.004694
2  -2.004694 -2.044694 -2.084694 -2.124694 -2.164694 -2.204694 -2.244694 -2.284694
3  -2.284694 -2.324694 -2.364694 -2.404694 -2.444694 -2.484694 -2.524694 -2.564694
4  -2.564694 -2.604694 -2.644694 -2.684694 -2.724694 -2.764694 -2.804694 -2.844694
5  -2.844694 -2.884694 -2.924694 -2.964694 -3.004694 -3.044694 -3.084694 -3.124694
6  -3.124694 -3.164694 -3.204694 -3.244694 -3.284694 -3.324694 -3.364694 -3.404694
7  -3.404694 -3.444694 -3.484694 -3.524694 -3.564694 -3.604694 -3.644694 -3.684694
8  -3.684694 -3.724694 -3.764694 -3.804694 -3.844694 -3.884694 -3.924694 -3.964694
9  -3.964694 -4.004694 -4.044694 -4.084694 -4.124694 -4.164694 -4.204694 -4.244694
10 -4.244694 -4.284694 -4.324694 -4.364694 -4.404694 -4.444694 -4.484694 -4.524694

Upvotes: 1

Related Questions