I am new to R so this is probably quite simple, but I am having an issue with the function I wrote- I need it to return an updated dataframe but it's returning the original.
I've created a function in R where the input is an 1) empty dataframe, signal
(with two columns, times
and import
, 2) a vector of days treatment is implemented (so for example, 30, 60, 90 means treatment was given on those days) and a 3) model_fit
, which brings in the curve that shows how treatment wears off over time. The output is the new dataframe that uses the vector of treatment days to bring in the data from model_fit
into the signal$import column and the corresponding times.
I tested out each line of my code for my function and they work- my issue is I can't figure out how to properly return the updated dataframe. Here's my code:
#Initial vectors for days post treatment, % killed
x <- c(4, 30, 60, 90, 120, 210, 360) #days post treatment
z <- c(1.0, 0.99, 0.99, 0.79, 0.7, 0.02, 0) #% killed
#create model fit:
fit2 <- nls(z ~ SSlogis(x, Asym, xmid, scal), data = data.frame(x, z))
summary(fit2)
lines(seq(0, 400, length.out = 400),
predict(fit2, newdata = data.frame(x = seq(0.5, 400, length.out = 400))))
# Create function:
trt.function <- function(model_fit, vector_of_trt_days, signal) {
#inputs
times <- seq(0, 20000, by = 1)
signal <- data.frame(times = times, import = rep(0, length(times)))
Asym<-summary(fit2)$parameters[1,1]
xmid<-summary(fit2)$parameters[2,1]
scal<-summary(fit2)$parameters[3,1]
trt.start = vector_of_trt_days
trt.end = c(trt.start + 400)
trt.segments <- unlist(Map(':', trt.start, trt.end))
time.segments <- rep(0:401, times=length(trt.start))
signal$import[trt.segments] = (Asym / (1 + exp((xmid - times[time.segments] / scal))))
return(signal)
}
This code keeps giving me an empty dataframe back. I'm know the code works when not in a function- the last line then returns the correct output. I tried using return(signal$import[trt.segments] = (Asym / (1 + exp((xmid - times[time.segments] / scal))))
but it gave me an error due to the =.
Can someone let me know how to return the new updated dataframe? I keep accidentally returning the original one. Thanks!
Just for reference, this code gives me the correct return outside the function:
#Create empty dataframe
times <- seq(0, 20000, by = 1)
signal <- data.frame(times = times, import = rep(0, length(times)))
# inputs
Asym<-summary(fit2)$parameters[1,1]
xmid<-summary(fit2)$parameters[2,1]
scal<-summary(fit2)$parameters[3,1]
trt.start <- c(10000,10090,10180,10270) #input for start times of treatments
trt.end <- c(trt.start + 400) #input for the end times of treatments
trt.segments <- unlist(Map(':', trt.start, trt.end)) #Create the treatment segments
time.segments <- rep(0:401, times=length(trt.start)) #create the corresponding time segments
signal$import[trt.segments] = (Asym / (1 + exp((xmid - times[time.segments]) / scal)))