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
Post a Comment