[R] join columns

Anthony Ching Ho Ng anthony.ch.ng at gmail.com
Wed Aug 10 17:04:35 CEST 2011


Dear R-help,

I wonder if you could give me some suggestions in how to do a union
join of two data frames as follow:
-> union join the common column, and insert a 0 if one is missing.

I made a function to perform the following, and I know it may not that
quite welly written, but it works.

Any suggestions are welcome, many thanks.

Anthony

> q1 = data.frame(a=1,b=2,c=3,row.names="q1")
     a b c
q1 1 2 3

> q2 = data.frame(d=4,b=1,a=4, row.names="q2")
     d b a
q2 4 1 4

->  myJoinColumns(q1,q2)
     a b c d
q1 1 2 3 0
q2 4 1 0 4


myJoinColumns <- function(q1,q2){
  allNames = sort(union(colnames(q1),colnames(q2)))
  for (i in 1:length(allNames)){
    t1 = which(colnames(q1) == allNames[i])
    t2 = which(colnames(q2) == allNames[i])

    if (length(t1) == 1){
      sec1 = q1[,t1]
    } else {
      sec1 = 0
    }

    if (length(t2) == 1){
      sec2 = q2[,t2]
    } else {
      sec2 = 0
    }

    if (i == 1){
      qTable = matrix(c(sec1,sec2))
    }else{
      qTable = cbind(qTable,c(sec1,sec2))
    }
  }
  colnames(qTable) = allNames
  rownames(qTable) = c("q1","q2")
  qTable
}



More information about the R-help mailing list