R語言控制結(jié)構(gòu)知識點總結(jié)
if(condition) true_expression else false_expression
if(condition) expression
因為表達式expression, true_expression, false_expression并非總是被執(zhí)行,因此if函數(shù)的類型是special
> typeof(`if`) [1] "special"
在R中.條件語句不是向量型運算
如果條件語句是由一個以上的邏輯值組成的向量,那么執(zhí)行語句時只會用到向量中的第一個元素
x = 10 y = c(8, 10, 12, 3, 17) if(x < y){ x }else{ y }
[1] 8 10 12 3 17 Warning message: In if (x < y) { : the condition has length > 1 and only the first element will be used
想要向量化操作需要使用ifelse函數(shù)
> ifelse(x < y, x, y) [1] 8 10 10 3 10
switch函數(shù)
swithcheroo.swith = function(x){ switch(x, a = "alligator", b = "bear" , c = "camel", "moose") }
> swithcheroo.swith("a") [1] "alligator" > swithcheroo.swith("f") [1] "moose"
循環(huán)語句
repeat
創(chuàng)建交互應用程序時用到
for
用于遍歷向量/列表的每一個項目
for(var in list) expression
- 循環(huán)內(nèi)的計算結(jié)果不打印在屏幕上,除非顯式地調(diào)用print
- var變量在命令環(huán)境中是變化的
循環(huán)擴展
迭代器iterators
通過擴展包iterators實現(xiàn)迭代器iterators
install.packages("iterators")
迭代器可以返回向量,數(shù)組,數(shù)據(jù)框或者其他對象的元素,甚至返回某個函數(shù)返回的值
iter函數(shù)創(chuàng)建迭代器:
參數(shù):iter(obj, checkFunc = function(...) T, recycle = F, ...)
- obj:指定對象
- by:
- chunksize:
- checkFunc:指定一個過濾迭代器返回值的函數(shù)
- recycle:指定當對象元素迭代完之后是否對迭代進行重置
- ...:
nextElem函數(shù):查看下一個迭代項,這個函數(shù)會隱式地調(diào)用 checkFunc
如果下一個值符合checkFunc,則返回該值
如果不符合,函數(shù)將試著返回另外一個值.nextElem函數(shù)會繼續(xù)檢查其他值,直到找到一個符合checkFunc的值.如果所有值都迭代完畢,沒有元素符合,迭代器會調(diào)用停止命令,并返回StopIteration
library(iterators) oneoffive = iter(1:5) > nextElem(oneoffive) [1] 1 > nextElem(oneoffive) [1] 2 > nextElem(oneoffive) [1] 3 > nextElem(oneoffive) [1] 4 > nextElem(oneoffive) [1] 5 > nextElem(oneoffive) Error: StopIteration
foreach循環(huán)
通過foreach包實現(xiàn)foreach循環(huán)
install.packages("foreach")
foreach能夠循環(huán)遍歷某個對象(向量,矩陣,數(shù)據(jù)框或者迭代器)中的多個元素 ,針對各個元素執(zhí)行表達式,并返回結(jié)果
在foreach函數(shù)內(nèi)部,將元素指定一個臨時值,與在for循環(huán)中的操作類似
function (..., .combine, .init, .final = NULL, .inorder = TRUE, .multicombine = FALSE, .maxcombine = if (.multicombine) 100 else 2, .errorhandling = c("stop", "remove", "pass"), .packages = NULL, .export = NULL, .noexport = NULL, .verbose = FALSE)
foreach函數(shù)返回一個foreach對象
想要真正地執(zhí)行循環(huán),需要使用
- %do%:順序執(zhí)行表達式
- 或%dopar%:并行執(zhí)行表達式
library(foreach) sqrts.1to5 = foreach(i = 1:5) %do% sqrt(i) sqrts.1to5 [[1]] [1] 1 [[2]] [1] 1.414214 [[3]] [1] 1.732051 [[4]] [1] 2 [[5]] [1] 2.236068
到此這篇關(guān)于R語言控制結(jié)構(gòu)知識點總結(jié)的文章就介紹到這了,更多相關(guān)R語言控制結(jié)構(gòu)詳解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!