R:两个数据框的笛卡尔积有什么函数?
R: any function for Cartesian Product of two data frames?
我需要计算两个数据框的笛卡尔积。例如,
A = id weight type
10 20 a
10 30 b
25 10 c
B = date report
2007 y
2008 n
然后 C 就像 A 和 B 的笛卡尔积
C = id weight type date report
10 20 a 2007 y
10 20 a 2008 n
10 30 b 2007 y
10 30 b 2008 n
25 10 c 2007 y
25 10 c 2008 n
因为有些id在A中是相同的,所以我不能使用像
这样的方式
C <- merge(A$id,B$date)
C <- merge(C,A,by="id")
C <- merge(C,B,by="date")
这种方式会生成更多的行。谁能帮我离开这里?谢谢
merge(A, B)
,如果没有链接两者的列,默认情况下应该这样做,不是吗?
来自 ?merge
(强调我的):
If by or both by.x and by.y are of length 0 (a length zero vector or NULL), the result, r, is the Cartesian product of x and y, i.e., dim(r) = c(nrow(x)*nrow(y), ncol(x) + ncol(y)).
诚然,这确实需要一个人知道要查看 ?merge
。 R 中严重缺乏基于上下文的搜索;甚至 rseek 也没有立即提供这个。
我需要计算两个数据框的笛卡尔积。例如,
A = id weight type
10 20 a
10 30 b
25 10 c
B = date report
2007 y
2008 n
然后 C 就像 A 和 B 的笛卡尔积
C = id weight type date report
10 20 a 2007 y
10 20 a 2008 n
10 30 b 2007 y
10 30 b 2008 n
25 10 c 2007 y
25 10 c 2008 n
因为有些id在A中是相同的,所以我不能使用像
这样的方式C <- merge(A$id,B$date)
C <- merge(C,A,by="id")
C <- merge(C,B,by="date")
这种方式会生成更多的行。谁能帮我离开这里?谢谢
merge(A, B)
,如果没有链接两者的列,默认情况下应该这样做,不是吗?
来自 ?merge
(强调我的):
If by or both by.x and by.y are of length 0 (a length zero vector or NULL), the result, r, is the Cartesian product of x and y, i.e., dim(r) = c(nrow(x)*nrow(y), ncol(x) + ncol(y)).
诚然,这确实需要一个人知道要查看 ?merge
。 R 中严重缺乏基于上下文的搜索;甚至 rseek 也没有立即提供这个。