首页 > 解决方案 > 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

标签: rfunctionset-difference

解决方案


#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])

更新:跟进

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

推荐阅读