在R中使用内部联接进行合并

在R中使用内部联接进行合并,r,R,对于下面使用内部联接合并两个表的代码,我得到了一个错误 table_Left<-matrix(c(1:6,rep("Toaster",3),rep("Radio",3)),ncol = 2) colnames(table_Left)<-c("Customer_ID","Product") table_Left<-as.table(table_Left) table_Left table_Right<-matrix(c(2,4,6,rep("Alabama",2),"Ohi

对于下面使用内部联接合并两个表的代码,我得到了一个错误

table_Left<-matrix(c(1:6,rep("Toaster",3),rep("Radio",3)),ncol = 2)
colnames(table_Left)<-c("Customer_ID","Product")
table_Left<-as.table(table_Left)
table_Left
table_Right<-matrix(c(2,4,6,rep("Alabama",2),"Ohio"),ncol = 2)
colnames(table_Right)<-c("Customer_ID","State")
table_Right<-as.table(table_Right)
table_Right
merge(x=table_Left, y=table_Right, by="Customer_ID")

table_Left我认为您的问题是由于对术语“table”的混淆。在使用R进行数据科学时,数据帧是一类非常常见的对象。而且,在通用语言中,它们通常被称为“表”。但是,您使用的函数
as.table()
与数据帧无关:
as.table()
创建列联表(这根本不是您想要的)

创建所需的两个数据帧(或“表”)的最有效方法是使用函数
data.frame()
直接创建它们:

现在,您的代码从创建矩阵开始。如果您有充分的理由在您的情况下使用矩阵,
merge()
也可以:

如果查看
merge()
函数(使用
?merge
)的帮助文件,您将看到:

合并(x,y,…)

x、 y:数据帧或要强制为一个的对象

矩阵可以强制为数据帧,而不会对数据造成任何问题。所以你也可以做:

ma_Left <- matrix(
  c(1:6, rep("Toaster", 3), rep("Radio", 3)), ncol = 2
)

colnames(ma_Left) <- c("Customer_ID", "Product")

ma_Right <- matrix(
  c(2, 4, 6, rep("Alabama", 2), "Ohio"), ncol = 2
)

colnames(ma_Right) <- c("Customer_ID", "State")

merge(x = ma_Left, y = ma_Right, by = "Customer_ID")

  Customer_ID Product   State
1           2 Toaster Alabama
2           4   Radio Alabama
3           6   Radio    Ohio

ma_\u Left如果您将
as.table
替换为
as.data.frame
.Ah!我正要发布一个带解释的答案,这时问题就解决了。我不认为这是重复的,因为OP试图合并表(而不是数据帧)。所以我想知道你是否会考虑重新开始这个问题。非常感谢。由于我无法发布我的答案,我只想在这里补充一点,即您不必将矩阵转换为数据帧:
merge()
将对数据帧起作用,但也对矩阵起作用,因为它们可以强制转换为数据帧(请看一下
?merge
)。因此,要使代码正常工作,只需删除将矩阵强制转换为表的行。也就是说,在创建数据时创建数据帧(使用
data.frame()
)而不是矩阵可能更合适(除非您有充分的理由创建矩阵)。
merge(x = df_Left, y = df_Right, by = "Customer_ID")

  Customer_ID Product   State
1           2 Toaster Alabama
2           4   Radio Alabama
3           6   Radio    Ohio
ma_Left <- matrix(
  c(1:6, rep("Toaster", 3), rep("Radio", 3)), ncol = 2
)

colnames(ma_Left) <- c("Customer_ID", "Product")

ma_Right <- matrix(
  c(2, 4, 6, rep("Alabama", 2), "Ohio"), ncol = 2
)

colnames(ma_Right) <- c("Customer_ID", "State")

merge(x = ma_Left, y = ma_Right, by = "Customer_ID")

  Customer_ID Product   State
1           2 Toaster Alabama
2           4   Radio Alabama
3           6   Radio    Ohio