R以交错(交叉)形式组合两个桌子

时间:2018-05-03 10:03:09

标签: r

我想在R

中合并两个表A和B.

A有col1 col2

B有colI colII

cbind()

你会得到

col1 col2 colI colII

我希望结果如下:

col1 colI col2 colII

这将有助于比较。

2 个答案:

答案 0 :(得分:1)

使用cbind函数是不可能的。您必须为此创建自己的逻辑。

# create table 1 
t1 <- table(letters[1:2], sample(letters[1:2]))
# create table 2
t2 <- table(letters[3:4], sample(letters[3:4]))
df1 <- data.frame(cbind(t1,t2))
df1[,names(df1)][c("a", "c", "b", "d")]
# Output as below
#  a c b d
#a 1 1 0 0
#b 0 0 1 1

答案 1 :(得分:0)

对于每个数据帧中只有两列,这种方法似乎最直接:

# create 2 dataframes with 2 columns each:
df1 <- data.frame(col1 = c(1, 2, 3), col2 = c(4, 5, 6))
df2 <- data.frame(coli = c(10, 20, 30), colii = c(40, 50, 60))
# bind them together in your order:
df3 <- data.frame(df1$col1, df2$coli, df1$col2, df2$colii)