Making pairwise matrix based on group value

Hey all,
How do I make a pairwise matrix based on group values. My final matrix should contain something like this: (pid1,pid3) (pid3,pid5) etc.
Below is sample code of the matrix I want to pair values.

mm <- matrix(0,10,3)
rownames(mm) <- rownames(mm, do.NULL = FALSE, prefix = "pID")
colnames(mm) <- c("orange", "mango","banana")
mm <- apply(mm, c(1,2), function(x) sample(c(0,1),1))
mm1 <- matrix(sample(seq(1,3),10,1))
colnames(mm1) <- c("group")
main <- cbind(mm,mm1)
main

Here is a solution using reshape2's melt to get the fruits into a single column along with group, filtering out the relevant records only then using aggregate to get the information you are looking for:

#defining matrix of variables
mm <- matrix(0,10,3)
rownames(mm) <- rownames(mm, do.NULL = FALSE, prefix = "pID")
colnames(mm) <- c("orange", "mango","banana")
mm <- apply(mm, c(1,2), function(x) sample(c(0,1),1))

mm1 <- matrix(sample(seq(1,3),10,1))
colnames(mm1) <- c("group")
mm1

main <- cbind(mm,mm1)
main

main <- as.data.frame(main)

main$pid <- rownames(main)
rownames(main) <- NULL

main_molten <- reshape2::melt(main, id.vars = c("pid", "group"))

relevant <- main_molten[main_molten$value == 1, ]

aggregate(relevant$pid, by=list(relevant$group, relevant$variable), FUN=paste)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.