不知道这个操作叫什么,谷歌也没有帮助。
假设我有两个像这样的简单数据框:
df1 <- data.frame(factor1 = c("a", "b", "c"))
df2 <- data.frame(factor2 = c("x", "y", "z"))
> df1
factor1
1 a
2 b
3 c
> df2
factor2
1 x
2 y
3 z
如何获得这样格式的数据框:
factor1 factor2
1 a x
2 a y
3 a z
4 b x
5 b y
6 b z
7 c x
8 c y
9 c z
我认为这种操作可能涉及乘以数据帧,但这不起作用:
> df1 * df2
factor1
1 NA
2 NA
3 NA
Warning message:
In Ops.factor(left, right) : ‘*’ not meaningful for factors
最佳答案
它是两个数据框的笛卡尔积,当没有共同的名字时,你可以使用merge
:
merge(df1, df2)
# factor1 factor2
#1 a x
#2 b x
#3 c x
#4 a y
#5 b y
#6 c y
#7 a z
#8 b z
#9 c z
或者更明确地说:
merge(df1, df2, by=c())
根据 ?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)).
关于R: 'Multiply' 数据帧字符串列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45557342/