How to generate all possible combinations of vectors without caring for order?
There's the combn
function in the utils
package:
t(combn(LETTERS[1:3],2))
# [,1] [,2]
# [1,] "A" "B"
# [2,] "A" "C"
# [3,] "B" "C"
I'm a little confused as to why your x
has duplicated values.
Generate all possible n choose 2 pairs from a vector in R, efficient and fast
As pointed out by @Arun, you can use combn
> t(combn(x, 2))
[,1] [,2]
[1,] 1 2
[2,] 1 3
[3,] 1 4
[4,] 2 3
[5,] 2 4
[6,] 3 4
How to get list of all combinations of pairs of character strings in R
An option is combn
combn(v1, 2, simplify = FALSE)
data
v1 <- paste0("pred_", 1:3)
How to list all permutations of events which happened in the right order?
I came to a similar conclusion using lapply
df <- lapply(1:nrow(events), function(x) {
expand.grid(events$name[x], events$name[(x+1):nrow(events)])})
do.call(rbind, df[-nrow(events)])
#> Var1 Var2
#> 1 sow water
#> 2 sow harvest
#> 3 water harvest
R: generate all permutations of vector without duplicated elements
Using gtools
package:
require(gtools)
permutations(n = 9, r = 3, v = 1:9)
# n -> size of source vector
# r -> size of target vector
# v -> source vector, defaults to 1:n
# repeats.allowed = FALSE (default)
R get all common elements for all possible combinations of N variables
Lots of ways, here's one:
grid <- expand.grid(a=c(T,F), b=c(T,F), c=c(T,F))
grid$results <- mapply(function(x,y,z) {
unique(c(if(x) a,if(y) b,if(z) c))
},grid$a,grid$b,grid$c)
Output:
a b c results
1 TRUE TRUE TRUE x1, x2, x3, x4, x5, x6
2 FALSE TRUE TRUE x2, x5, x3, x4, x6
3 TRUE FALSE TRUE x1, x2, x3, x4, x6
4 FALSE FALSE TRUE x3, x4, x6
5 TRUE TRUE FALSE x1, x2, x3, x4, x5
6 FALSE TRUE FALSE x2, x5
7 TRUE FALSE FALSE x1, x2, x3, x4
8 FALSE FALSE FALSE NULL
Generate all possible combinations of rows in R?
You can combine all the data as below:
do.call(cbind.data.frame,Map(expand.grid,teacher=teachers,students=students))
name.teacher name.students height.teacher height.students smart.teacher smart.students
1 Ben John 130 111 yes no
2 Craig John 101 111 yes no
3 Mindy John 105 111 yes no
4 Ben Mary 130 93 yes no
5 Craig Mary 101 93 yes no
6 Mindy Mary 105 93 yes no
: : : : : : :
: : : : : : :
Related Topics
Add Error Bars to Show Standard Deviation on a Plot in R
How to Remove Unicode <U+00A6> from String
Remove Duplicates Keeping Entry with Largest Absolute Value
Multiplying All Elements of a Vector in R
Dynamically Build Call for Lookup Multiple Columns
Position of the Sun Given Time of Day, Latitude and Longitude
Using Gsub to Extract Character String Before White Space in R
How to Generate a Matrix of Combinations
Change Colors in Ggpairs Now That Params Is Deprecated
Export a List into a CSV or Txt File in R
Why Is As.Date Slow on a Character Vector
Converting Excel Datetime Serial Number to R Datetime
Seeing If Data Is Normally Distributed in R
How to Choose Variable to Display in Tooltip When Using Ggplotly