[R] data frame solution
Andras Farkas
motyoc@k@ @end|ng |rom y@hoo@com
Tue Mar 19 12:06:22 CET 2019
Hello All,
wonder if you have thoughts on a clever solution for this code:
df <- data.frame(a = c(6,1), b = c(1000,1200), c =c(-1,3))
#the caveat here is that the number of rows for df can be anything from 1 row to in the hundreds. I kept it to 2 to have minimal reproducible
t<-seq(-5,24,0.1) #min(t) will always be <=df$c[1], which is the value that is always going to equal to min(df$c)
times1 <- c(rbind(df$c[1],df$c[1]+df$a[1]),max(t)) #length of times1 will always be 3, see times2 is of length 4
input1 <- c(rbind(df$b[1]/df$a[1],rep(0,length(df$b[1]))),0) #length of input1 will always be 3, see input2 is of length 4
out1 <-data.frame(t,ifelse(t>=times1[1]&t<times1[2],input1[1],ifelse(t>=times1[2]&t<times1[3],input1[2],input1[3])))
times2 <- c(times1[1],rbind(df$c[2],df$c[2]+df$a[2]),max(t)) #note 1st value of times2, (or for times3, times4,.. if more rows in df) is times1[1], which will always be < times2[1] (or times3[1], times4[1],.. if more rows in df)
input2 <- c(0,rbind(df$b[2]/df$a[2],rep(0,length(df$b[2]))),0) #note 1st value of input2 (or for input3, input4,.. if more rows in df) is 0, which will always be 0 (or for all input2-n other then for input1 as that will be as above ,.. if more rows in df)
out2 <-data.frame(t,ifelse(t>=times2[1]&t<times2[2],input2[1],ifelse(t>=times2[2]&t<times2[3],input2[2],ifelse(t>=times2[3]&t<times2[4],input2[3],input2[3]))))
result<-data.frame(t,out1[,2]+out2[,2])
so if I did it all manually then for row 3 in df I would calculate out3 and so on... Would like to be able to do this with a clean function solution that allows for different row numbers in df...
as always your help is appreciated
thanks
Andras
More information about the R-help
mailing list