我试图将列的所有排列作为数据帧传递给函数,但我无法让我的代码正常工作。有人有什么建议吗?
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){}))
Run Code Online (Sandbox Code Playgroud)
目标
dataframe containing col:
1
2
3
4
1,2
1,3
1,4
2,3
2,4
....
Run Code Online (Sandbox Code Playgroud)
我的功能:
#takes in dataframe of columns
blackBox<-function(x){}
Run Code Online (Sandbox Code Playgroud)
因为我最初的解释不够清楚:我试图将每种情况下返回的列放入数据帧中,以便我可以对数据做一些事情。
#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)
})
Run Code Online (Sandbox Code Playgroud)
我们可以遍历列的顺序,得到combn了的unlstED元素和使用rapply,以paste在每个嵌套的元素list。
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)
Run Code Online (Sandbox Code Playgroud)
如果我们需要用列名替换'v1',我们可以尝试用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"
Run Code Online (Sandbox Code Playgroud)
或者它也可以combn通过传递names而不是值来完成。
lst <- lapply(seq_along(Un1), function(i) combn(names(Un1), i, simplify=FALSE))
v1 <- rapply(lst, toString)
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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
647 次 |
| 最近记录: |