I'm new to R, this might be a dumb question, but I don't know how to solve it.
I have a for loop that will possibly return i * j non-empty elements.
I want to save all non-empty result in a list, but if I use result[[i]]<-tmp in a loop, it can only store i elements, how can I 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
Answer to david
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
source share