Skip to content
Prev 81769 / 398502 Next

combine two columns

Hello,

Following should work.

m <- matrix(round(runif(16,0,2)),nrow=2)
colnames(m) <- c("A","A","B","B","C","C","D","D")
m2 <- m #matrix(, nrow=dim(m)[1], ncol=dim(m)[2]/2)
z <- 1
ss <- seq(1,dim(m)[2],2)

for(j in ss){
  for(i in 1:dim(m)[1]){
    m2[i,j] <- substring(m[i,ss[z]] == m[i,ss[z]+1],1,1)
  }
  z <- z + 1
}
m2 <- m2[,ss]
colnames(m2) <- colnames(m)[ss]

When your data set is large, then you should try to code this using
apply.

Best,
Matthias