重塑数据框,使列的每个条目重复所有其他列

Reshape dataframe so that each entry of column in repeated over all other columns

我有一个 data.frame, dat, 看起来像这样

dat = data.frame(x = c(1, 1.1, 1.2, 1.3), y = c(2, 2.1, 2.2, 2.3), output = c(2, 10, 101, 100))
    x   y output
1 1.0 2.0      2
2 1.1 2.1     10
3 1.2 2.2    101
4 1.3 2.3    100

我希望 "x" 和 "output" 列的每对元素在 "y" 列上重复。

我尝试使用 tidyr::spreadtidyr::gatherreshape2::melt 都无济于事。这是因为我是使用 tidyrreshape2 以及其他整形包的初学者。

目前,我使用循环从列 "x" 和 "output" 中提取每个元素对,并创建一个新的 data.frame、final_df,它结合了结果 data.frames。我相信这绝对不是最有效的方法,并且我相信某个地方有一个单行函数可以为我做这个魔术。

在生成的 data.frame 中,如果我使用 say

对 data.frame 进行子集化
dplyr::filter(final_df, x == 1, output == 2)

它应该是这样的:

data.frame(x = rep(1, dat$x[1], nrow(dat)), y = dat$y, output = rep(dat$output[1], nrow(dat)))
  x   y output
1 1 2.0      2
2 1 2.1      2
3 1 2.2      2
4 1 2.3      2

我很乐意使用 tidyverse 回答。谢谢。

这是一个选项

library(dplyr)
library(tidyr)
dat %>% mutate(y1=paste(y,collapse = ',')) %>% separate_rows(y1)

如果 xoutput 中没有重复,即我们可以将它们视为 ID 列然后我们可以使用 tidyr::complete

dat %>% complete(nesting(x,output),y)

一个解决方案:

require(dplyr)
require(tidyr)
 dat %>% select(-y) %>% crossing(dat %>% select(y))
     x output   y
1  1.0      2 2.0
2  1.0      2 2.1
3  1.0      2 2.2
4  1.0      2 2.3
5  1.1     10 2.0
6  1.1     10 2.1
7  1.1     10 2.2
8  1.1     10 2.3
9  1.2    101 2.0
10 1.2    101 2.1
11 1.2    101 2.2
12 1.2    101 2.3
13 1.3    100 2.0
14 1.3    100 2.1
15 1.3    100 2.2
16 1.3    100 2.3