Convert this for loop to an apply function R -


i have vector of data such following:

data <- c(1, 3, 4, 7) 

and apply function every pair of elements in vector such return upper triangle matrix following does:

mat <- matrix(data = na, nrow = length(data), ncol = length(data)) (i in 1:(length(data) - 1)) {   (j in (i+1):length(data)) {     mat[i, j] <- "-"(data[j], data[i])   } } 

but apply type function instead of loop.

i unsure how so. suggestions?

thanks!

we can use combn

mat[lower.tri(mat, diag=false)] <- combn(data, 2,                             fun= function(x) x[2]-x[1]) t(mat) #      [,1] [,2] [,3] [,4] #[1,]   na    2    3    6 #[2,]   na   na    1    4 #[3,]   na   na   na    3 #[4,]   na   na   na   na 

data

mat <- matrix(data = na, nrow = length(data), ncol = length(data)) 

Comments

Popular posts from this blog

SVG stroke-linecap doesn't work for circles in Firefox? -

routes - Laravel 4 Wildcard Routing to Different Controllers -

cross browser - XSLT namespace-alias Not Working in Firefox or Chrome -