R: 'Multiply' 数据帧字符串列

标签 r dataframe

不知道这个操作叫什么,谷歌也没有帮助。

假设我有两个像这样的简单数据框:

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/

相关文章:

r - 在 Python 中使用 R 和 Rpy2 : how to ggplot2?

r - 首先按组总和对数据帧进行排序,然后按频率排序

r - R语言能找到一阶微分方程的通解吗?

r - 尝试调整R中Apriori算法的外观

python - 在包含列表的数据框中搜索值

r - 如何有选择地乘以列

python - Pandas DataFrame - 计算每行中的 0

R:如何在 ggplot2 线图中重新排序图例键以匹配每个系列中的最终值?

r - 将 R 列值扩展为具有另一列值的列标题

python - 使用来自另一个 pandas DF 的最小值的 id 填充 pandas 列