比如兩個變量i,j
i=1:4 j=1:30
公式y(tǒng)=j+10i
計算出的y是矩陣
這個循環(huán)該怎么寫呢?
解:
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
}
}
一個更簡潔的方法:
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 ## 等后面的語句只有一行,則無需使用花括號。
}
if(method == "subtract"){
res <- a - b
}
return(res) ## 返回值
}
### 檢驗結(jié)果
fun.test(a = 10, b = 8, method = "add")
fun.test(a = 10, b = 8, method = "substract")
for循環(huán)有些時候是必須要用到的,for循環(huán)內(nèi)部,往往需要用下標,訪問數(shù)據(jù)內(nèi)的一定元素,例如向量內(nèi)的元素,這時候用方括號表示。一維的數(shù)據(jù)組合,或者數(shù)組,常常稱為向量。二維的數(shù)據(jù)組合,往往稱為矩陣,或者數(shù)據(jù)框。具體的訪問方式主要是方括號內(nèi)部有沒有逗號的區(qū)別。for循環(huán)或者while循環(huán)有時候讓人覺得比較困惑,可能需要專門的時間進行講解。








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