[R] 'splice' two data frames

Peter Wolf s-plus at wiwi.uni-bielefeld.de
Thu Aug 25 11:26:02 CEST 2005


what about:

@
<<*>>=
z<-data.frame(matrix(rbind(x,y),nrow(x),2*ncol(x)))
rownames(z)<-rownames(x)
z
@
output-start
Thu Aug 25 11:24:29 2005
  X1   X2 X3   X4 X5   X6 X7   X8
a  2 0.02  1 0.01  2 0.02  2 0.02
b  3 0.03  0 0.00  4 0.04  3 0.03
c  3 0.03  2 0.02  1 0.01  6 0.06
d  3 0.03  4 0.04  2 0.02  3 0.03
e  4 0.04  1 0.01  4 0.04  2 0.02
f  2 0.02  5 0.05  2 0.02  2 0.02
g  4 0.04  5 0.05  3 0.03  3 0.03
h  3 0.03  3 0.03  5 0.05  4 0.04
i  1 0.01  0 0.00  3 0.03  3 0.03
output-end

Peter Wolf


David Whiting wrote:
>Hi,
>
>I often need to take columns from two data.frames and 'splice' them
>together (alternately taking a column from the first data frame, then
>from the second). For example:
>
>x <- table(sample(letters[1:9], 100, replace=TRUE),
>           sample(letters[1:4], 100, replace=TRUE))
>y <- prop.table(x)
>
>splice <- function (x, y) {
>  z <- matrix(rep(NA, (ncol(x) * 2) * nrow(x)), nrow = nrow(x))
>  j <- 1
>  for (i in seq(1, ncol(z), by = 2)) {
>    z[, i] <- x[, j]
>    z[, (i + 1)] <- y[, j]
>    j <- j + 1
>  }
>  z <- data.frame(z)
>  rownames(z) <- rownames(x)
>  z
>}
>
>splice(x, y)
>
>
>Manually using indexing I can do this:
>
>zz <- data.frame(x[, 1], y[, 1], x[, 2], y[, 2], x[, 3], y[, 3], x[, 4],
>y[, 4])
>
>
>I *feel* that it should be possible in R to generate the sequence of
>column indexes automatically. I can get close with this:
>
>i <- paste("x[,", 1:ncol(x), "], ",
>	   "y[,", 1:ncol(y), "]",
>	   collapse=", ")
>
>which creates a string version of what I want, but I am not sure how to
>use that with data.frame. FAQ 7.21 ("How can I turn a string into a
>variable?") looked promising but I have not been able to apply any of
>the suggestions to this problem. I also tried using do.call:
>
>i <- paste("x[,", 1:4, "],", "y[,", 1:4, "]", collapse=",")
>i <- gsub("],", "]@", i)  # Create a marker for
>i <- strsplit(i, "@")     # strsplit to create a list
>do.call(data.frame, i)
>
>and with lapply:
>
>lappy(i, data.frame)
>
>These "did not work" (i.e. they worked as they were designed to and did
>not give me the results I am after).
>
>I think I need a nudge or two in the right direction.
>
>Thanks.
>
>Dave
>
>




More information about the R-help mailing list