基于不同子网合并数据框
DF <- mtcars
## subsets
df1 <- subset(DF, carb == 1)
df2 <- subset(DF, am == 1)
## table
table1 <- prop.table(with(df1, table(cyl, gear)), margin = 1)
table2 <- prop.table(with(df2, table(cyl, vs)), margin = 1)
## total
total <- cbind(table1 , table2)
这将导致:
Error in cbind(B5A2, B5A3) :
number of rows of matrices must match (see arg 2)
我正在尝试基于MTCARS数据集的两个不同子网(DF1,DF2)合并这两个数据帧(Table1,Table2)。到目前代码>两者都无法使用。有办法解决这个问题吗?
首选的输出应该看起来像这样:
cyl 3 4 0 1
4 0.2 0.8 0,125 0.875
6 1.0 0.0 1.000 0.000
8 1.000 0.000
谢谢!
DF <- mtcars
## subsets
df1 <- subset(DF, carb == 1)
df2 <- subset(DF, am == 1)
## table
table1 <- prop.table(with(df1, table(cyl, gear)), margin = 1)
table2 <- prop.table(with(df2, table(cyl, vs)), margin = 1)
## total
total <- cbind(table1 , table2)
which results in:
Error in cbind(B5A2, B5A3) :
number of rows of matrices must match (see arg 2)
I'm trying to merge (preferably by cols ) those 2 data frames (table1 , table2) based on two different subets (df1, df2) from the mtcars dataset. I've tried so far: convert to data.frame
and use bind.cols
and plyr::rbind.fill.matrix(table1, table2)
which both didn't work. Is there a way to fix this?
The preferred output should look like this:
cyl 3 4 0 1
4 0.2 0.8 0,125 0.875
6 1.0 0.0 1.000 0.000
8 1.000 0.000
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从
gdata
软件包中使用cbindx
函数:代码:
在2022-07-05创建的 reprex软件包(v2.0.1)
You could use the
cbindX
function from thegdata
package:Code:
Created on 2022-07-05 by the reprex package (v2.0.1)
您也可以用作实际
tibbles
/data.frames*(我正在使用Janitor
'stabyl
在此处使用),然后做一个完整的加入
(我正在使用dplyr
)。输出:
(*)当您编写“ 2个数据帧(Table1,Table2)”时,您并不完全正确。您的表是表,而不是数据帧,这不是相同的。使用
as.dataframe(表)
将为您提供table
以另一种格式组织的数据,更适合其他类型的分析。You could also construct your frequency tables as actual
tibbles
/data.frames* (I am usingjanitor
'stabyl
here) and then do afull join
(I am usingdplyr
).Output:
(*) When you write "2 data frames (table1 , table2)", you're not completely right. Your tables are tables, not data frames, which is not the same. Using
as.dataframe(table)
will give you the data in thetable
organized in another format better suited for other kinds of analysis.