lapply在使用自定义函数时返回NULL

时间:2014-04-24 15:37:13

标签: r lapply

我经历过一个类似的问题,更多的是效率低下而不是失败,但是使用lapply解决了here

(编辑)的 我这次包含了垃圾数据的工作代码,这会在运行时抛出错误。下面的代码按原样工作,但是我想用最后的#' d lapply函数替换if(numruns == ...)语句。 使用func_ign_time的lapply分配NULL值。 我也遇到了f​​unc_drop_time的一些错误,但它们可能是相关的。

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

1 个答案:

答案 0 :(得分:2)

当你想要一个向量(显然)时,你将一个char变量传递给func_ign_time(...)。换句话说,你做的相当于:

func_ign_time("pyro_1")

何时需要

func_ign_time(pyro_1)

请改为尝试:

lst <- list(pyro_1, pyro_2,pyro_3)
lapply(ign_names, func_ign_time)

或者,尝试:

lapply(mget(ign_names), func_ign_time)