I have a binary matrix and I want to merge column an and b for example. If there is a 1 and a 0 then the output should be 1. 0 and 0 should stay 0, but 1 and 1 should also stay 1.
a b c
a 1 0 1
b 0 0 0
c 1 1 1
so in the end it should look like this
ab c
a 1 1
b 0 0
c 1 1
how can I do that?
I was thinking about the paste function to create a new column but I don’t want the output to be 11, 01 , 00 but only one number
>Solution :
You can achieve the desired result by using the pmax function in R, which is used to take element-wise maximum of multiple vectors. In this case, you can use pmax to compare corresponding elements of columns "a" and "b" and create a new column "ab" with the maximum value of each pair.
Here’s the code to merge columns "a" and "b" into a new column "ab" in your binary matrix:
# Create the binary matrix
matrix <- matrix(c(1, 0, 1, 0, 0, 1, 1, 0, 1), nrow = 3, ncol = 3, byrow = TRUE)
colnames(matrix) <- c("a", "b", "c")
rownames(matrix) <- c("a", "b", "c")
# Merge columns "a" and "b" into "ab"
matrix$ab <- pmax(matrix$a, matrix$b)
# Remove columns "a" and "b"
matrix <- matrix[, c("ab", "c")]
# Print the resulting matrix
print(matrix)
The resulting merged_matrix will have the columns ab and c:
ab c
a 1 1
b 0 0
c 1 1
The resulting matrix has a new column "ab" that contains the merged values of columns "a" and "b", following the rules you specified.