0
有人可以幫我解決這個問題嗎?我收到這個錯誤:Error in if (numList[i]%%2 != 0) { : missing value where TRUE/FALSE needed
。我知道這意味着我的一些數據是NA,但我不知道如何解決這個問題。在讀文件功能中需要TRUE/FALSE時缺少值
我想要做的是讀三個文件,計算所有奇數的平均值並將這些值保存到'average.txt'文件。
我的代碼:其中錯誤發生
calcAvg <- function(numList) {
oddList <- c()
for (i in 1:length(numList)) {
if(numList[i] %% 2 != 0) {
oddList = c(oddList, numList[i])
}
}
avg <- mean(oddList)
return(format(round(avg,2), nsmall =2))
}
而且功能: 功能來calc下的平均
writeToFile <- function() {
file.create("average.txt", showWarnings = TRUE)
myFile <- file("average.txt", open="w")
f = file.path(getwd(), c("data1.txt", "data2.txt", "data3.txt"))
d <- lapply(f, readFile)
str(d)
allNumAvg = calcAvg(as.numeric(unlist(d))) < --- error points on this line after traceback
data1 = calcAvg(as.numeric(unlist(readFile("data1.txt"))))
data2 = calcAvg(readFile("data2.txt"))
data3 = calcAvg(readFile("data3.txt"))
write(allNumAvg, myFile, append=TRUE)
write((data1), myFile, sep = "\n")
write((data2), myFile, sep = "\n")
write(data3, myFile)
close(myFile)
}
謝謝!
它的作品!謝謝! – Jakubee