Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store result in list from a for loop

Tags:

loops

r

I'm new to R, this may be a silly question, but I don't know how to resolve.

I have a for loop which will return possibly i*j non-empty elements.

I want to store all the non-empty result in a list, but if I use result[[i]]<-tmp in the loop, it can only store up to i elements, how am I able to store all values in a list? Thanks

  result<-list()
  for (i in 1:nrow(m)){
    for (j in 1:i){
      if(m[i,j]!=0 && m[j,i]!=0){
        num=min(m[i,j],m[j,i])
        tmp=c(i,j,num)
        result[[i]]<-tmp
      }
    }
  }

sample data
set.seed(123)
m= matrix(sample(0:5, size = 5*5, replace = TRUE), ncol = 5)

Desired

 row col min
[1] 1 1 1
[1] 2 2 3
[1] 3 1 2
[1] 3 2 2
[1] 3 3 4
[1] 4 1 5
[1] 4 2 1
[1] 4 4 1
[1] 5 1 5
[1] 5 2 2
[1] 5 4 5
[1] 5 5 3

Per David's answer

pmin(mx[upper.tri(mx, diag = TRUE)], mx[lower.tri(mx, diag = TRUE)])

[1] 1 0 2 5 2 3 5 1 0 1 3 0 1 5 3

returns

      > result
[[1]]
[1] 1 1 2

[[2]]
[1] 2 2 3

[[3]]
[1] 3 3 4

[[4]]
[1] 4 4 2

[[5]]
[1] 5 5 4
like image 524
qshng Avatar asked May 07 '15 19:05

qshng


People also ask

How do you insert values into a list in a for loop?

In your for loop, the n variable is your index into the array, so change arr[value] = input("Enter value") to arr[n] = input("Enter value") . Side note: Any values added this way will be strings and not integers. Same as (2) for your second for loop, print(arr[value]) should be print(arr[n]) .

Can we use for loop for list?

Using Python for loop to iterate over a list. In this syntax, the for loop statement assigns an individual element of the list to the item variable in each iteration. Inside the body of the loop, you can manipulate each list element individually.


1 Answers

Here's something like @DavidArenburg's answer (converted from a comment):

idx <- which(upper.tri(m,diag=TRUE),arr.ind=TRUE)
v   <- pmin(m[idx], m[idx[,2:1]])

cbind(idx,min=v)[v>0,]

which gives

      row col min
 [1,]   1   1   1
 [2,]   2   2   3
 [3,]   1   3   2
 [4,]   2   3   2
 [5,]   3   3   4
 [6,]   1   4   5
 [7,]   2   4   1
 [8,]   4   4   1
 [9,]   1   5   5
[10,]   2   5   2
[11,]   4   5   5
[12,]   5   5   3
like image 168
2 revs Avatar answered Oct 06 '22 00:10

2 revs