我已經工作的處理,以創建用於長度1:n
唯一整數的所有可能的組合中選擇列/行的元件。我發現了nCr
函數(combinat包中的combn函數在這裏很有用)。使用從一個表中作爲R
一旦所有獨特出現被重複,它們被附加到包含任何可能的長度+組合的數字1:n
一個合併表。最後的表的相應列(一個記錄)的一個子集是這樣的(列名爲字符串和集表f1
):
c(1,3,4,5,9,10)
我需要從一個輔助數據源選擇這些列(df
)一個在一段時間(我通過這個表要循環),所以我的邏輯是使用此代碼:
df[,f1$String]
不過,我得到一個消息,說是未定義列選擇,但如果我複製並粘貼細胞內容如:
df[,c(1, 3, 4, 5, 9, 10)]
它工作得很好...我已經嘗試了所有我可以在此時想到的;如果有人有一些洞察力,將不勝感激。
代碼來重現是:
library(combinat)
library(data.table)
library(plyr)
rm(list=ls())
NCols=10
NRows=10
myMat<-matrix(runif(NCols*NRows), ncol=NCols)
XVars <- as.data.frame(myMat)
colnames(XVars) <- c("a","b","c","d","e","f","g","h","i","j")
x1 <- as.data.frame(colnames(XVars[1:ncol(XVars)]))
colnames(x1) <- "Independent.Variable"
setDT(x1)[, Index := .GRP, by = "Independent.Variable"]
colClasses = c("character", "numeric", "numeric")
col.names = c("String", "r!", "n!")
Combination <- read.table(text = "", colClasses = colClasses, col.names = col.names)
for(i in 1:nrow(x1)){
x2<- as.data.frame(combn(nrow(x1),i))
for (i in 1:ncol(x2)){
x3 <- paste("c(",paste(x2[1:nrow(x2),i], collapse = ", "), ")", sep="")
x3 <- as.data.frame(x3)
colnames(x3) <- "String"
x3 <- mutate(x3, "r!" = nrow(x2))
x3 <- mutate(x3, "n!" = nrow(x1))
Combination <- rbind(Combination, x3)
}
}
setDT(Combination)[, Index := .GRP, by = c("String", "r!", "n!")]
f1 <- Combination[717,]
f1$String <- as.character(f1$String)
## reference to data frame
myMat[,(f1$String)]
## pasted element
myMat[, c(1, 3, 4, 5, 9, 10)]
你能提供'$ F1的String'的輸出? – ANG
請提供一個可重複的例子。 –
F1 $串的輸出爲:c(1,3,4,5,9,10) – Anton89