以下是优化后的代码:

above.select <- function(tmp.csv){ tmp.path <- paste0('testtd/', tmp.csv) tmp.gp <- read.csv(tmp.path) if (any(abs(tail(tmp.gp$td,4))>0.3)) { tmp.zx <- tail(tmp.gp, 20) %>% filter(abs(td)>0.3) %>% summarise(meanzx=mean(meanzx)) if(tmp.zx$meanzx > 0){ tmp.above <- (tail(tmp.gp$meanzx,1)-tmp.zx$meanzx)*100/tmp.zx$meanzx tmp.code <- substr(tmp.csv, start = 13,stop = 18) tmp.dataf <- data.frame(code=tmp.code,above=tmp.above) return(tmp.dataf) } } return(NULL) }

主要的优化如下:

1.将读取csv文件和路径拼接的代码合并为一行。

2.使用tail函数代替filter和slice,提高代码效率。

3.使用summarise函数代替select和mean,提高代码效率。

4.增加了tmp.zx$meanzx > 0的判断,避免除数为0的情况。

5.使用return函数显式返回结果,避免不必要的计算和内存使用。

最后,建议在函数中增加异常处理机制,以防止程序崩溃。

R语言代码优化:above.select 函数改进

原文地址: https://www.cveoy.top/t/topic/lCoS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录