Home > Net >  Add conditions on frequency of each value to expand grid in R
Add conditions on frequency of each value to expand grid in R

Time:07-28

I want to create a table of available combination using colours

library(tidyr)

#give available colour combo
colour= c("BK", "CS", "DB","DG","LB","LG","MV","OR","RD","WT","YL","ID","EMPTY")

combo = expand.grid(colour, colour,colour, colour)
#function "colnames" to change column names
colnames(combo) <- c('A','B','C','D')

What I want is a condition on the 2 last colours "ID" and "EMPTY" The condition is that for each combination, so for each line they are aloud to be in only 1 column (A,B,C or D) at a time. So their frequency is 0.25. But they also need to be in at least 1 column.

CodePudding user response:

If order does not matter:

library(combinat)
library(data.table) # for rbindlist

colour <- c("BK", "CS", "DB","DG","LB","LG","MV","OR","RD","WT","YL")
combo <- setnames(as.data.table(t(combn(colour, 2))), c("A", "B"))[, c("C", "D") := .("ID","EMPTY")]
head(combo)
#>     A  B  C     D
#> 1: BK CS ID EMPTY
#> 2: BK DB ID EMPTY
#> 3: BK DG ID EMPTY
#> 4: BK LB ID EMPTY
#> 5: BK LG ID EMPTY
#> 6: BK MV ID EMPTY

If order does matter, simply permute the columns of combo:

combo <- rbindlist(lapply(permn(4), function(x) combo[, ..x]), FALSE)

CodePudding user response:

Sir @George.I give one example Definition What does ROW mean? (Right Of Way) @Andre230 the ID and Empty with available combination with colour list above. I think my ROW is a valid example for your Condition on the 2 last colours ID and EMPTY. Only 1 column (A.B.C or D)at the time. Their frequency is 0.25. But you also need to be in at least 1 column. The letter (R) is the important for this quiz/test.

  • Related