R:“乘以”字符串的数据框列 [英] R: 'Multiply' dataframe columns of strings
问题描述
不确定该操作的名称,Google并没有帮助。
Not sure what this operation is called, and Google did not help.
说我有两个简单的数据框,例如:
Say I have two simple dataframes like this:
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
我如何获得这样格式的数据框:
How can I get a dataframe formatted like this:
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
我认为这种操作可能涉及将数据帧相乘,但这不起作用:
I would think that this kind of operation might involve multiplying the dataframes, but this does not work:
> df1 * df2
factor1
1 NA
2 NA
3 NA
Warning message:
In Ops.factor(left, right) : ‘*’ not meaningful for factors
推荐答案
这是笛卡尔积这两个数据帧中的,如果没有通用名称,则可以使用 merge
:
It's a cartesian product of the two data frames, when there's no common names, you can use 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())
根据合并
,当没有要连接的列时,它返回两个数据帧的<笛卡尔乘积:
According to ?merge
, when there are no columns to join by, it returns a cartesian product of the two data frames:
如果by.x和by.y或两者的长度均为0(长度为零)向量或
NULL),结果r是x和y的笛卡尔积,即
dim(r)= c(nrow(x)* nrow(y),ncol(x) + ncol(y))。
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:“乘以”字符串的数据框列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!