6
votes

I find myself wanting to sometimes paste together columns from different dataframes (tables, matrices or whatever). For example I have a table of means and a table of stan devs. I want the two pasted together with the sd in a set of parentheses for latex printing. I suspect there's a friendly plyr solution but can't think of how to work on two data frames ( I attempted storing the dataframes as a list and using ldply but this was my first attempt with a list plyr function and it went down in flames.

Thank you in advance.

#=========
#fake data
#=========
x<-mtcars[1:3,1:3]
y<-mtcars[1:3,8:10]


#==========================
#A column pasting function
#==========================
meansd<-function(x, y){
x<-round(x, dig=2)
y<-round(y, dig=2)
paste(x, "(", y, ")", sep="")
}

That's as far as I got.

DESIRED OUTCOME No column names needed. I don't care if the return is a matrix or dataframe.

16.46(0)  0(1)  1(4)
17.02(0)  0(1)  1(4)
18.61(1)  1(1)  1(4)
3
if you are looking to use this to produce regression summary tables in latex, then do take a look at mtable in the package memisc. it is a very flexible function that allows you to output your regression output in multiple formats with minimal effort. - Ramnath
@Ramnath Thank you for your comment. I became familiar with this package just recently. It does a great deal of what I want for latex output but there's still a few things I need the flexibility to to some things mtable can't. - Tyler Rinker
Are you going to xtable the resulting data.frame? - Ari B. Friedman
can you specify more clearly what is the output format you are looking at. mtable is super-flexible and it beats me that it can't do something standard :) - Ramnath
@gsk Yes I'll use xtable with the solution (#3 solution [yours] is the one I like best; base package and simple), but I'll add some tweaks to it and make it one funtion that takes a means and sd table and produces a publishable means table.. Thanks for your solution. - Tyler Rinker

3 Answers

8
votes

How about mapply?

x <- mtcars[1:3,1:3]
y <- mtcars[1:3,8:10]

mypaste <- function(x,y) paste(x, "(", y, ")", sep="")

mapply(mypaste, x,y)

     mpg       cyl    disp    
[1,] "21(0)"   "6(1)" "160(4)"
[2,] "21(0)"   "6(1)" "160(4)"
[3,] "22.8(1)" "4(1)" "108(4)"
7
votes

Here is an approach using plyr

t(ldply(1:NCOL(x), function(i) meansd(x[,i], y[,i])))
4
votes

Here is your function edited to loop through and paste each column. This gives your desired result, but there is probably a cleverer way to do this.

meansd<-function(x, y){
    x<-round(x, digits = 2)
    y<-round(y, digits = 2)
    out <- matrix(ncol = dim(x)[1], nrow = dim(x)[2])
    for(i in 1:dim(x)[1])
    {
        out[i, ] <-paste(x[i, ], "(", y[i, ], ")", sep="")
    }
    return(out)
}