在R中存储嵌套循环的输出

时间:2014-07-27 16:42:35

标签: r for-loop output

我是R的新手,但却拼命地学习绳索。事实上,我觉得有点愚蠢地问这个问题,因为我经历了一些类似的问题,但未能取得预期的结果。我的代码如下所示:

## Initializing Parameters

fstart <- 960   ## Start frequency in MHz
fstop <- 1240   ## Stop Frequency In MHz
bw <- 5.44      ## IF Bandwidth in MHz
offset <- 100   ## Max. Variation in TOD in milliseconds
f_dwell <- 1    ## Time spent on each search frequency in millisecond
iterations <- 100 ## No. of iterations to run

## No. of possible frequencies 

f <- seq((fstart + bw/2), (fstop - bw/2), by=bw)

## Initializing the frequency table

freq_table <- matrix (NA, nrow=(2*offset +1), ncol=offset)

## Fill frequency table row wise with random values of possible frequencies

for (i in 1:(2*offset + 1)){

row_value <- c(sample(f), sample(f, offset-length(f)))
freq_table[i, ] <- row_value
}

## Assign a row from freq_table to unknown node

unknown_node <- freq_table[sample(1:(2*offset + 1), 1), ]
t = numeric(iterations)
## Calculate number of repetitions of frequencies
for(k in 1:iterations){
for(j in 1:offset){

    y <- (sort(table(freq_table[, j]), decreasing=TRUE))
    x <- as.vector(y)       ## Number of repetitions of each frequency
    y <- names(y)

## Search Frequencies

sf1 <- as.numeric(y[1])
sf2 <- as.numeric(y[2])

    if (unknown_node[j] == sf1){
    t[k] <- ((j-1)*f_dwell)*2 + f_dwell
break
    }
    else {
  if (unknown_node[j] == sf2){
    t[k] <- ((j-1)*f_dwell)*2 + 2*f_dwell
    break
    }
    }
## Delete rows from freq_table that have sf1 & sf2

freq_table <- subset(freq_table, freq_table[, 1]!=sf1 & freq_table[, 1]!=sf2 )
}

}

print(t)

如果我在没有k for循环的情况下运行它,我每次都得到不同的变量t值。但是,我希望迭代地运行内部for循环,并在每次内部for循环运行时获得t值的向量。我确实得到t的长度为100,但值重复。前几个值(2 0r 3或有时4)是不同的,但其余值不断重复。我无法弄清楚原因。

0 个答案:

没有答案