2012-03-13 114 views
5

我想保存邏輯測試循環中的數據。R中循環:如何保存輸出?

所以,我有以下數據:

T1 <- matrix(seq(from=100000, to=6600000,length.out=676),26,26) # a matrix of 26X26 - here with illustrive values 

minmax <- seq(from=1,to=49,by=1) # creates a sequence 
Fstep <- 6569141.82/minmax  # define a vector from 0 to 6569141.82 with 49 divisions 
F <- rev(round(Fstep,0))   # round the vector values and re order them 
F 

我已經拼命地跑下面的循環

for (i in 1:49) { 
    print(T1 > F[i]) # I used print to see the results in the screen 
} 

這個循環返回我49點矩陣與邏輯值(TRUE或FALSE)填寫。每個矩陣是T1與49個位置F [i](F [1],...,F [49])中的每一個的比較。

我需要在那些矩陣中有值,以便進一步使用網絡圖的鄰接矩陣。但是,如果我既不能將這些邏輯值分配給矩陣,也不能使用「write.matrix」將它們保存爲csv值。

所以,我需要有49個矩陣「W」填入邏輯值(T或F)。我已經通過上面的循環獲取了這些值,但我無法將其作爲對象或作爲csv的集合。文件。

我試圖

W<-matrix(0,26,26) #create an empty matrix to assign the logical arguments 
for (i in 1:49){ 
    W[i] <- T1>F[i] # I used print to see the results in the screen 
} 

返回以下警告

Warning messages: 
1: In W[i] <- (T1 > F[i]) : 
    number of items to replace is not a multiple of replacement length 

我也試過在所有我比較矩陣具有相同的尺寸不同的設置。

create.M <- function(F){ # a function to transform each position F[i] into a 26X26 matrix 
    for (i in 1:49) { 
    matrix(F[i],26,26) 
    } 
} 

Loop.T1 <- function(T1){ # a function to replicate T1(49 times) 
    for (i in 1:49) { 
    T1 
    } 
} 

並比較這兩個輸出

Loop.T1(T1)>create.M(F) 

返回

logical(0) 
+0

如果你要使用for循環,你需要學習該轉讓是必要的循環中。否則沒有什麼持久的「發生」。 – 2012-03-13 18:03:22

回答

7

存儲每個布爾矩陣作爲項目列表中:

result <- vector("list",49) 
for (i in 1:49) 
{ 
    result[[i]] <- T1>F[i] # I used print to see the results in the screen 
} 

#Print the first matrix on screen 
result[[1]] 
6

另一種方法什麼喬蘭暗示給我們e應用功能家族。

result2 <- lapply(F, function(f) {T1 > f}) 

這給出了同樣的事情joran的result,其中每個元素對應於F的值之一以及元件是爲26x26邏輯矩陣的列表。

另一種選擇是將結果存儲爲三維邏輯矩陣(49 * 26 * 26),其中每個片段對應於F的值之一。其中

result3 <- sapply(F, function(f) {T1 > f}, simplify="array") 

結構

> str(result3) 
logi [1:26, 1:26, 1:49] FALSE FALSE FALSE FALSE TRUE TRUE ... 
+1

偉大的布萊恩。 Result2效果很好!我將進一步研究申請家庭的文件和它的語法。 – 2012-03-13 19:56:24