Tyler Rinker
Tyler Rinker

Reputation: 109864

Paste columns of two data frames

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)

Upvotes: 7

Views: 1574

Answers (3)

Ari B. Friedman
Ari B. Friedman

Reputation: 72731

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)"

Upvotes: 10

Ramnath
Ramnath

Reputation: 55695

Here is an approach using plyr

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

Upvotes: 7

Ryan Taylor
Ryan Taylor

Reputation: 56

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)
}

Upvotes: 4

Related Questions