Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paste columns of two data frames

Tags:

r

plyr

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)
like image 497
Tyler Rinker Avatar asked Nov 03 '11 01:11

Tyler Rinker


People also ask

How do I paste two DataFrames in R?

To join two data frames (datasets) vertically, use the rbind function. The two data frames must have the same variables, but they do not have to be in the same order. If data frameA has variables that data frameB does not, then either: Delete the extra variables in data frameA or.

How do I combine columns from a different DataFrame in R?

Method 1 : Using plyr package rbind. fill() method in R is an enhancement of the rbind() method in base R, is used to combine data frames with different columns. The column names are number may be different in the input data frames. Missing columns of the corresponding data frames are filled with NA.

How do I merge two data frames?

The concat() function in pandas is used to append either columns or rows from one DataFrame to another. The concat() function does all the heavy lifting of performing concatenation operations along an axis while performing optional set logic (union or intersection) of the indexes (if any) on the other axes.


2 Answers

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)"
like image 90
Ari B. Friedman Avatar answered Nov 20 '22 01:11

Ari B. Friedman


Here is an approach using plyr

t(ldply(1:NCOL(x), function(i) meansd(x[,i], y[,i])))
like image 29
Ramnath Avatar answered Nov 20 '22 00:11

Ramnath