'create matrix based on apply function in R
I have a matrix in R like this
dat <- matrix(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1), ncol = 4)
and i want to calculate the local variant (lv) of mutual information. For a pair of columns I can use the following code to find the lv
dat <- dat[,c(1,2)]
#install.packages("rinform")
library(rinform)
library(devtools)
#install_github("ELIFE-ASU/rinform")
#install_github("ELIFE-ASU/rinform", ref = "dev")
library(rinform)
mutual_info(dat)
mi <- mutual_info(dat, local = T)
mi <- as.matrix(mi)
which results in:
> mi
[,1]
[1,] -1.0000000
[2,] -1.0000000
[3,] 0.2223924
[4,] 0.2223924
[5,] 0.2223924
[6,] 0.2223924
[7,] 0.2223924
[8,] 0.2223924
[9,] 0.2223924
[10,] 0.2223924
[11,] 0.2223924
[12,] 0.2223924
[13,] 0.2223924
[14,] 0.2223924
[15,] 0.2223924
[16,] 0.2223924
[17,] 1.5849625
[18,] 1.5849625
[19,] 1.5849625
[20,] -1.5849625
How can I create a matrix that each column will have the mi values of each pair? Tried to use an apply function but couldn't make it work. The output result must be a 20x6 matrix with all pair-wise column combinations, i.e., the above mi procedure for dat[,c(1,2)], dat[,c(1,3)], dat[,c(1,4)], dat[,c(2,3)], dat[,c(2,4)], dat[,c(3,4)]. Can someone help me?
Solution 1:[1]
I can't verify this approach since I don't know the rinform package. You could try
apply(combn(1:4, 2), 2, function(i) mutual_info(dat[, i], locale = TRUE))
combn(1:4, 2)creates a matrix of all possible of two elements from1:4.- We use this as an input for the
applyfunction to generate the result.
Naming
If you save the new data into a matrix
new_data <- apply(combn(1:4, 2), 2, function(i) mutual_info(dat[, i], locale = TRUE))
you could name the columns using the same approach:
colnames(new_data) <- apply(combn(1:4, 2), 2, function(i) paste0("V", i, collapse = ""))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
