我试图将列的所有排列作为数据帧传递给函数,但我无法让我的代码工作。有人有什么建议吗?
require(combinat)
indicators<-data.frame(a=c(1),b=c(2),c=c(3),d=c(4))
cols<-lapply(1:dim(indicators)[2],function(x)rbind(t(permn(1:(dim(indicators)[2]-x)))))
cols[[2]]
temp<-t(apply(cols[[2]],1,function(x){}))
目标
dataframe containing col:
1
2
3
4
1,2
1,3
1,4
2,3
2,4
....
我的功能:
#takes in dataframe of columns
blackBox<-function(x){}
因为我原来的解释不够清楚:我试图将每种情况下返回的列放到数据帧中,这样我就可以对数据做些什么。
#testing only with the first 12 values because otherwise it takes forever
lapply(v1[1:12],function(x){
colsCombo<-indicators[,c(eval(parse(text=x)))]
colnames(colsCombo)
})
答案 0 :(得分:4)
我们可以循环遍历列的序列,获取combn
ed元素的unlst
并使用rapply
到paste
每个嵌套{中的元素{1}}。
list
如果我们需要用列名替换'v1',我们可以尝试使用Un1 <- unlist(indicators)
lst <- lapply(seq_along(Un1), function(i) combn(Un1, i, simplify=FALSE))
v1 <- rapply(lst, toString)
v1
#[1] "1" "2" "3" "4" "1, 2" "1, 3" "1, 4" "2, 3"
#[9] "2, 4" "3, 4" "1, 2, 3" "1, 2, 4" "1, 3, 4" "2, 3, 4" "1, 2, 3, 4"
d1 <- data.frame(v1, stringsAsFactors=FALSE)
将索引替换为列名。
chartr
或者也可以通过传递rp1 <- paste(colnames(indicators),collapse="")
pt1 <- paste(seq_along(Un1), collapse="")
chartr(pt1, rp1, v1)
#[1] "a" "b" "c" "d" "a, b" "a, c" "a, d" "b, c"
#[9] "b, d" "c, d" "a, b, c" "a, b, d" "a, c, d" "b, c, d" "a, b, c, d"
代替值来在combn
内完成。
names