【问题标题】:Build a data frame that has unique combinations of all variations [duplicate]构建一个具有所有变体的独特组合的数据框[重复]
【发布时间】:2017-02-15 00:48:40
【问题描述】:

我正在构建一些示例数据,并且需要能够为 3 个变量因子的每个组合提供一些数据。

我有 3 个向量,每个向量都有 3 个排列:

fruit <- c("pears", "apples", "grapes")
veg <- c("carrots", "cabbages", "broccoli")
pets <- c("cats", "dogs", "fish")

然后我有一些虚拟数据:

Date_Range <- seq(as.Date("2017-01-01"), as.Date("2017-01-30"), by = 1),
Sessions <- ceiling(rnorm(90, mean = 3000, sd = 300))

我现在想用这些构建一个数据框。对于 Date_Range 中的 30 个日期中的每一个,我希望存在一种水果、蔬菜和宠物的不同组合。

我怎样才能以这种方式构建?

【问题讨论】:

  • 你能提供一个预期的输出示例吗?
  • Sessions 向量的意义何在?你根本没提。
  • @Gregor 只是一个与这些因子变量一起显示的指标。实际用例是网站数据,实际向量是登录页面、设备类别(移动设备、台式机、平板电脑)和渠道(谷歌、Facebook 等)。
  • 查看expand.grid函数:expand.grid(Date_Range, fruit, veg, pets)
  • @Dave2e 你也需要Date_Range

标签: r


【解决方案1】:

我想我得到了 27 种组合。我忽略了Sessions

d = t(combn(c(fruit,pets,veg),3))
x = rep(0, nrow(d))
for (i in 1:nrow(d)){
    if ( any(d[i,] %in% fruit) & any(d[i,] %in% pets) & any(d[i,] %in% veg) ){
    x[i] = 1
    }
}
d = d[x == 1,]

n = nrow(d) * length(Date_Range)
DATE = rep(Date_Range,nrow(d))

D = d[rep(seq_len(nrow(d)), each=NROW(Date_Range)),]
OUTPUT = cbind(D,DATE)
head(OUTPUT)
#                              DATE   
#[1,] "pears" "cats" "carrots" "17167"
#[2,] "pears" "cats" "carrots" "17168"
#[3,] "pears" "cats" "carrots" "17169"
#[4,] "pears" "cats" "carrots" "17170"
#[5,] "pears" "cats" "carrots" "17171"
#[6,] "pears" "cats" "carrots" "17172"

【讨论】:

  • OP 也想要date_range 在那里。
  • 您好,感谢您抽出宝贵时间回答。不确定这里的礼仪。为了简单起见,我更喜欢 cmets 中给出的答案,使用 expand.grid,但我不能接受评论!
  • @d.b 哦,好的。还是谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-24
  • 1970-01-01
相关资源
最近更新 更多