Search code examples
rfunctionset-difference

Using a function to create a new dataframe with unused elements


I have two vectors with three elements. There are twenty total combinations of taking all six elements and rearranging them into different sets of two vectors with three elements. I need to write R code that will do that.

My current code sets the two vectors, combines them into one vector, creates a dataframe with all twenty combinations of a single vector of size three. I'm now trying to write a function that will create the second vector of size three by comparing each of the twenty vectors to the vector with all elements, and seeing which elements are unused (setdiff). However, I keep getting an empty new vector. Please help.

drug<-c(36, 60, 39)
placebo<-c(73, 55, 70)
drugandplacebo<-c(drug,placebo)
drugandplacebo
number<-1:20
t(number)
allcombdrug<-combn(drugandplacebo,3)
allcombdrug
tallcombdrug<-t(allcombdrug)
tallcombdrug
tallcombdrub<-data.frame(tallcombdrub)
tallcombdrug

func1 <- function(tallcombdrug) {
  allcorespplac <- data.frame()  

  for (i in 1:length(tallcombdrug)) { 
    allcorespplac[i] <- setdiff(drugandplacebo,tallcombdrug[i])
  }
}
func1
allcorespplac

Solution

  • #list with all all combinations of three
    l1 <- combn(c(drug, placebo),3,simplify = FALSE)
    #list with all remaining values not in l1
    l2 <- lapply(l1, function(x) c(drug,placebo)[!c(drug,placebo) %in% x])
    

    UPDATE: follow-up

    library(data.table)
    cbind(
      data.table::rbindlist( lapply( l1, as.data.frame.list ) ),
      data.table::rbindlist( lapply( l2, as.data.frame.list ) )
    )