我发现自己有时希望将来自不同数据框(表格,矩阵或其他)的列粘贴在一起。例如,我有一个手段表和stan devs表。我希望将这两个与sd粘贴在一组用于乳胶印刷的括号中。我怀疑有一个友好的plyr解决方案,但无法想到如何处理两个数据帧(我试图将数据帧存储为列表并使用ldply但这是我第一次尝试使用列表plyr函数,它在火焰中熄灭。
提前谢谢。
#=========
#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="")
}
就我而言。
渴望成为 不需要列名。我不在乎返回是矩阵还是数据帧。
16.46(0) 0(1) 1(4)
17.02(0) 0(1) 1(4)
18.61(1) 1(1) 1(4)
答案 0 :(得分:7)
以下是使用plyr
t(ldply(1:NCOL(x), function(i) meansd(x[,i], y[,i])))
答案 1 :(得分:7)
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)"
答案 2 :(得分:4)
这是您编辑的函数,用于循环并粘贴每一列。这给出了你想要的结果,但可能有一种更聪明的方法来做到这一点。
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)
}