简体   繁体   中英

Loop in R: how to save the outputs?

I am trying to save the data from a loop of logical tests.

So I have the following data:

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

I have runned the following loop

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

This loop returns me 49 matrices filled in with logical values (True or false). Each matrix is the comparison of T1 against each of the 49 positions F[i] (F[1], ...., F[49])

I need to have the values in those matrices for further using as adjacency matrices for network plots. However when I can't neither assign those logical values to an matrix, neither save them in csv values using "write.matrix".

So, I need to have 49 - matrices "W" filled in with logical values (T or F). I already got those values by the loop above but I can't get it as an object or as collection of csv. files.

I tried

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
}

which returns the following warning

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

I also tried a different setting in which all the matrices I compare have the same dimensions.

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
  }
}

and compared the two outputs

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

which returns

logical(0)

Store each boolean matrix as an item in a list:

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]]

Another way to do what joran suggests is to use the apply family of functions.

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

This gives the same thing as joran's result , a list where each element corresponds to one of the values of F and that element is a 26x26 logical matrix.

Another alternative is to store the results as a three dimensional logical matrix (49*26*26) where each slice corresponds to one of the values of F .

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

the structure of which is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM