I wrote a program that takes more than one vector as arguments. If I input a single vector as an input the function provides the following error message:
Error in combn(letters[1:length(mylist)], 2) : n < m
Called from: combn(letters[1:length(mylist)], 2)
I know why I am getting this error. I have used a combination function combn that chooses 2 vectors. How do I fix this? I want to get an output even if my input is a single vector. In this case, I want my code to skip those lines that need 2 vectors and run the rest to get an output. I am providing my entire code here for convenience.
### Function to check whether two sets a,b are incomparable
incomparable <- function(a,b){
cond1 <- sum(a>b) > 0 # Returns true is if there is at least one case such that a_i is 1 and b_i is 0
cond2 <- sum(b>a) > 0 # True if at least one case such that one case with b_i is 1 and a_i is 0
ifelse (length(a)== length(b), cond1*cond2, "Strings are not of the same length")
}
incomparable(a,b)
### Function to get subsets of a binary vector
binary_subset<-function(a){
a_seq = lapply(a, seq, 0) # keep 0s as 0, make 1s c(1, 0)
subset=do.call(expand.grid, a_seq)
colnames(subset)=(1:length(a))
return(subset)
}
#### Function to generate all lower-order interaction terms correspond to interaction terms a,b,c...upto any arbitrary number L (including terms a, b, c...L)
all_lower_order_interactions<-function(...){
mylist <- list(...)
combination<-combn(letters[1:length(mylist)], 2) #choose 2 out of L vectors
check_incomparable<-0
for (j in 1:ncol(combination)){
check_incomparable[j]<- (incomparable(get(combination[1,j]), get(combination[2,j])))
}
check_incomparable
if(all(check_incomparable>0)==FALSE) {stop( "at least one of the interaction terms is a special case (or a subset) of another term.")}
interactions_abc <- do.call("rbind", lapply(mylist, binary_subset))
interactions_no_duplicate <- unique(interactions_abc[1:length(mylist[[1]])])
rownames(interactions_no_duplicate) <- 1:nrow(interactions_no_duplicate)
interactions_no_duplicate
}
a<-c(0,1,0)
b<-c(0,0,1)
all_lower_order_interactions(a)
combination<-combn(letters[1:length(mylist)], 2)? - starja