Loop in R: how to save outputs?

I am trying to save data from a logic test cycle.

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 performed the following cycle

 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 with logical values โ€‹โ€‹(True or false). Each matrix is โ€‹โ€‹a comparison of T1 with each of the 49 positions F [i] (F [1], ...., F [49])

I need to have values โ€‹โ€‹in these matrices for future use as adjacency matrices for network diagrams. However, when I can neither assign these booleans to the matrix, nor store them in csv values โ€‹โ€‹using "write.matrix".

So, I need to have a 49-matrix "W" filled with logical values โ€‹โ€‹(T or F). I already got these values โ€‹โ€‹in the loop above, but I can't get it as an object or csv collection. 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 another setting in which all matrices matched 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 two outputs

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

which returns

 logical(0) 
+6
source share
2 answers

Store each logical matrix as an element 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]] 
+7
source

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

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

This gives the same thing as joran result , a list in which each element corresponds to one of the values โ€‹โ€‹of F , and this element is a 26x26 logical matrix.

Another alternative is to save 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") 

whose structure

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

Source: https://habr.com/ru/post/910618/


All Articles