Reputation: 897
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
Upvotes: 6
Views: 2103
Reputation: 66819
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
Upvotes: 3