本題自學。我找到了,但是當它說沒有奇數時回傳 0 時我卡住了。
uj5u.com熱心網友回復:
oddnumbers <- function(data) {
sumodd <- c(0)
for(i in data) {
if (i %% 2 != 0) {
sumodd = sumodd i
}
}
return (sumodd)
}
如果您需要任何解釋,請告訴我!
uj5u.com熱心網友回復:
R 是一種基于向量的語言,因此在許多情況下,R 可以避免使用回圈。
oddnumbers <- function(data) {
#identify the odd numbers data %%2 !=0
#identify the index of the odd numbers which(...)
#filter the odds data[...]
sum(data[(which(data %%2 !=0))])
}
testdata <- trunc(runif(20, 1, 100))
oddnumbers(testdata)
使用which()和內置矢量化sum()函式,執行速度將比 R 回圈快 1000 倍。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/333078.html
標籤:r
上一篇:R-ddplyr未按預期作業-按類別對長格式資料進行shapiro.test
下一篇:從寬到長,變數前沒有X
