【文章內(nèi)容簡介】
2 3 4 5 6 $y [,1] [,2] [1,] 1 3 [2,] 2 4 ? 列表子集的提出取 ?提取一個(gè)子對象如 foo的 x,下面三種方式等價(jià) foo$x foo[1] foo[[1]] 例子 foo$y foo[2] foo[[2]] foo[[1]][2] foo$y[2] foo$y[4] ?條件語句 ? 作用 : 避免除零或負(fù)數(shù)的對數(shù)等數(shù)學(xué)問題 ? 形式 1: if (條件 ) 表達(dá)式 1 else 表達(dá)式 2 ? 形式 2 – 常優(yōu)于形式 1! ifelse(條件 , yes, no) 試比較下面的三個(gè)結(jié)果: x = c(6:4) sqrt(ifelse(x = 0, x, NA)) ifelse(x = 0, sqrt(x), NA) if (x = 0) sqrt(x) else NA ? 循環(huán) (loops) ? for() 若知道終止條件 for (變量 in 向量 ) 表達(dá)式 ? while() 若無法知道運(yùn)行次數(shù) while(條件 ) 表達(dá)式 ? 兩者通??梢赞D(zhuǎn)換 例 1—試比較兩種方法 for (i in 1:5) print (1:i) i=1 while(i = 5) { + print(1:i) + i = i+1 + } 例 2 – 見 KoKang Wang’s ―R Programming Workshop‖, pp68 ? Suppose we generate a pseudo DNA microarray and we want to do an ANOVA on it. First we generate some factors for Array (a), Treatments (t) and Genes (g). Then generate some normal random numbers for the logged foreground intensity. Then we put into an aov() function for each gene – this is where the loop is good for. Note that you will get different answer when you try it, because of the random numbers generated. 程序如下 (使用 for循環(huán),也可改用 while循環(huán) ): 注: R控制面板中顯示符號 和 +,而源程序中是不需要的! n = 3044 a = c(rep(1, 2 * n), rep(2, 2 * n)) t = c(rep(1, n), rep(2, n), rep(2, n), rep(1, n)) g