3 回答
TA贡献1828条经验 获得超3个赞
这也许是你想要的
> expand.grid(a,b)
Var1 Var2
1 ABC 2012-05-01
2 DEF 2012-05-01
3 GHI 2012-05-01
4 ABC 2012-05-02
5 DEF 2012-05-02
6 GHI 2012-05-02
7 ABC 2012-05-03
8 DEF 2012-05-03
9 GHI 2012-05-03
10 ABC 2012-05-04
11 DEF 2012-05-04
12 GHI 2012-05-04
13 ABC 2012-05-05
14 DEF 2012-05-05
15 GHI 2012-05-05
如果得到的订单不是您想要的,那么您可以随后进行排序。如果您将参数命名为expand.grid,它们将成为列名:
df = expand.grid(a = a, b = b)
df[order(df$a), ]
和expand.grid概括为任意数量的输入列。
TA贡献1841条经验 获得超3个赞
这个tidyr软件包提供了一个不错的选择crossing,这比经典的要好得多。expand.grid函数,因为(1)字符串没有转换为因子,(2)排序更直观:
library(tidyr)
a <- c("ABC", "DEF", "GHI")
b <- c("2012-05-01", "2012-05-02", "2012-05-03", "2012-05-04", "2012-05-05")
crossing(a, b)
# A tibble: 15 x 2
a b
<chr> <chr>
1 ABC 2012-05-01
2 ABC 2012-05-02
3 ABC 2012-05-03
4 ABC 2012-05-04
5 ABC 2012-05-05
6 DEF 2012-05-01
7 DEF 2012-05-02
8 DEF 2012-05-03
9 DEF 2012-05-04
10 DEF 2012-05-05
11 GHI 2012-05-01
12 GHI 2012-05-02
13 GHI 2012-05-03
14 GHI 2012-05-04
15 GHI 2012-05-05
TA贡献1852条经验 获得超1个赞
library(data.table)CJ(a = a, b = b, unique = TRUE)
a b 1: ABC 2012-05-01 2: ABC 2012-05-02 3: ABC 2012-05-03 4: ABC 2012-05-04 5: ABC 2012-05-05 6: DEF 2012-05-01 7: DEF 2012-05-02 8: DEF 2012-05-03 9: DEF 2012-05-0410: DEF 2012-05-0511: GHI 2012-05-0112: GHI 2012-05-0213: GHI 2012-05-0314: GHI 2012-05-0415: GHI 2012-05-05
CJ(a, b, unique = TRUE)
options("datatable.CJ.names" = TRUE)
- 3 回答
- 0 关注
- 518 浏览
添加回答
举报