比如兩個(gè)變量i,j
i=1:4 j=1:30
公式y(tǒng)=j+10i
計(jì)算出的y是矩陣
這個(gè)循環(huán)該怎么寫(xiě)呢?
解:
i <- 1:4; j <- 1:30; # i and j
ni<- length(i); nj <- length(j) # lengths of i and j
y <- matrix(NA, nj, ni) # initiate a matrix with nj rows and ni columns
for (k in 1:ni){
for (p in 1:nj){
y [p, k] <- i[k] * 10 + j[p] # fill the matrix
}
}
一個(gè)更簡(jiǎn)潔的方法:
matrix(rep(i, each=nj) * 10+rep(j, ni), nj, ni)
例子1
## if與條件判斷
fun.test <- function(a, b, method = "add"){
if(method == "add") { ## 如果if或者for/while;
res <- a + b ## 等后面的語(yǔ)句只有一行,則無(wú)需使用花括號(hào)。
}
if(method == "subtract"){
res <- a - b
}
return(res) ## 返回值
}
### 檢驗(yàn)結(jié)果
fun.test(a = 10, b = 8, method = "add")
fun.test(a = 10, b = 8, method = "substract")
for循環(huán)有些時(shí)候是必須要用到的,for循環(huán)內(nèi)部,往往需要用下標(biāo),訪問(wèn)數(shù)據(jù)內(nèi)的一定元素,例如向量?jī)?nèi)的元素,這時(shí)候用方括號(hào)表示。一維的數(shù)據(jù)組合,或者數(shù)組,常常稱(chēng)為向量。二維的數(shù)據(jù)組合,往往稱(chēng)為矩陣,或者數(shù)據(jù)框。具體的訪問(wèn)方式主要是方括號(hào)內(nèi)部有沒(méi)有逗號(hào)的區(qū)別。for循環(huán)或者while循環(huán)有時(shí)候讓人覺(jué)得比較困惑,可能需要專(zhuān)門(mén)的時(shí)間進(jìn)行講解。








暫無(wú)數(shù)據(jù)