I've experienced a similar problem more along the lines of being inefficient rather than than failing to function, it was solved here using lapply.
(Edited) I'm including working code with junk data this time that will throw the error back when run. The code below works as is, however I would like to replace the if (numruns ==... ) statements with the #'d lapply functions at the very end. The lapply using func_ign_time assigns NULL values. I'm also encountering some errors with the func_drop_time, but they may be related.
numruns = 3
pyro_1 <- as.numeric(c(100,70,50,2,3,4,60,160,260,360,503))
pyro_2 <- as.numeric(c(100,100,100,70,50,2,3,4,60,160,260,360,503))
pyro_3 <- as.numeric(c(100,100,70,50,2,3,4,60,160,260,360,503))
time_diff <- seq(1,100,1)
func_ign_time <- function(data, delay = 5, threshold = 5, time="time_diff"){
diff_data <- diff(data[1:length(data)])
flag <- 0
for (i in 1:length(diff_data)){
if (diff_data[i] > threshold && diff_data[i+1] > threshold && i > delay){
flag <- 1
time <- as.numeric(time_diff[i])
#print(paste0("Plug ignition time: ", time, " seconds"))
return (time)
}
}
}
func_drop_time <- function(data, threshold = -5, time="time_diff"){
diff_data <- diff(data[1:length(data)])
flag <- 0
for (i in 1:length(diff_data)){
if (diff_data[i] < threshold && flag == 0){
flag <- 1
time <- as.numeric(time_diff[i])
#print(paste0("Plug drop time: ", time, " seconds"))
return(time)
}
}
}
if (numruns == 3){
time_ign_3 <- as.numeric(func_ign_time(pyro_3)-func_drop_time(pyro_3))
time_ign_2 <- as.numeric(func_ign_time(pyro_2)-func_drop_time(pyro_2))
time_ign_1 <- as.numeric(func_ign_time(pyro_1)-func_drop_time(pyro_1))
print(paste(time_ign_1,time_ign_2,time_ign_3))
}
if (numruns == 2){
time_ign_2 <- as.numeric(func_ign_time(pyro_2)-func_drop_time(pyro_2))
time_ign_1 <- as.numeric(func_ign_time(pyro_1)-func_drop_time(pyro_1))
print(paste(time_ign_1,time_ign_2))
}
if (numruns == 1){
time_ign_1 <- as.numeric(func_ign_time(pyro_1)-func_drop_time(pyro_1))
print(paste(time_ign_1))
}
#ign_names <- paste0("pyro_", seq_len(numruns))
#xx <- lapply(ign_names, function(x) (func_ign_time(x)))
#yy <- lapply(ign_names, function(x) (func_drop_time(x)))
#zz <- xx-yy
lapply
to callfunc_ing_time
, but thereturn
value offunc_ing_time
is nested within a loop. You can only return one value from a function; are you expecting thefunc_ing_time
function to return multiple values? If so, then you should replace thefor
loop within the func_ing_time with a call tolapply
orsapply
. Again, it would be easier to help you if you posted code that runs. – FascinatingFingerspyro_x
, a vector or a data frame? Check out this guideline to learn about how to ask a great question. – tonytonov