r - 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
解决方案
#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 ) )
)
推荐阅读
- linux - 如何在某些网页上使用 linux 命令行来获取图像加载时间?
- c# - 如何在列表中查找重复项
并将它们的值相加 - javascript - 选择要在 div 中显示为 bg-img 的图像
- git - 如何将项目上传到特定标签?
- sql-server - 显示PowerPoint幻灯片时刷新文本框
- c - osx 和/或 linux 上的进程范围命名属性
- shell - go executable 以某种方式确定了错误的 GOROOT
- escaping - 无法正确转义 KNIME 中的规则
- angular - ngx-translate Angular 变量值问题
- python - 选择用于复制 Pandas DataFrame 的列