[英]How to enumerate all combinations in a matrix in R?
我們可以在outer
使用expand.grid
data.frame(expand.grid(a, b), c = c(outer(a, b, "+")))
# Var1 Var2 c
#1 1 1 2
#2 8 1 9
#3 1 4 5
#4 8 4 12
#5 1 9 10
#6 8 9 17
哪里
outer(a, b, "+") #gives
# [,1] [,2] [,3]
#[1,] 2 5 10
#[2,] 9 12 17
好的,這是:
z <- outer(b, a, "+")
cbind(a[col(z)], b[row(z)], c(z))
# [,1] [,2] [,3]
#[1,] 1 1 2
#[2,] 1 4 5
#[3,] 1 9 10
#[4,] 8 1 9
#[5,] 8 4 12
#[6,] 8 9 17
一種稍微適應的expand.grid
解決方案。
ref <- expand.grid(b = b, a = a)
val <- do.call("+", ref) ## or `rowSums(ref)` with an implicit `as.matrix`
cbind(ref, c = val)
# b a c
#1 1 1 2
#2 4 1 5
#3 9 1 10
#4 1 8 9
#5 4 8 12
#6 9 8 17
在這種情況下,結果是數據幀而不是矩陣。
或另一種選擇是CJ
library(data.table)
CJ(a, b)[, C := V1 + V2][]
#. V1 V2 C
#1: 1 1 2
#2: 1 4 5
#3: 1 9 10
#4: 8 1 9
#5: 8 4 12
#6: 8 9 17
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.