我有一个由 3 个字母组成的向量 (testCol_1)。每个字母都是二进制的,可以用 0 或 1 替换。
规则是,如果一个字母(例如 S)被数字(例如 1)替换,则向量中的所有 S 也将被同一数字替换。
我想找到所有可能的组合;对于以下可重现的示例,有 8 种可能的组合。
test <- expand.grid(rep(list(c("S","E","F")),4))
testCol_1 <- test$Var1
我的解决方案:
这是我自己的解决方案,但正如您所看到的,这相当新手,我确信有更好的方法来解决这个问题。
# Changing to integer
testCol_1 <- as.integer(testCol_1)
# Finding all the combinations first
temp.combo <- expand.grid(rep(list(0:1),3))
test.final.result <- list()
for (i in 1:nrow(temp.combo)){
testSol <- replace(testCol_1, testCol_1 == 1,temp.combo[i,1])
testSol <- replace(testSol, testSol == 2,temp.combo[i,2])
testSol <- replace(testSol, testSol == 3,temp.combo[i,3])
test.final.result[[i]] <- testSol
}
最佳答案
这是一个没有循环的解决方案,使用 R 的向量化指令直接从 temp.combo
获取 0/1,通过对其进行子集化,运行以下命令来查看它:
temp.combo[, testCol_1]
另请注意,nvals
并不是严格需要的,它只会使代码更具可读性。
test <- expand.grid(rep(list(c("S","E","F")), 4))
testCol_1 <- as.integer(test$Var1)
nvals <- length(unique(testCol_1))
temp.combo <- expand.grid(rep(list(0:1), nvals))
temp <- as.data.frame(t(temp.combo[, testCol_1]))
test.final.result <- as.list(temp)
test.final.result
#> $V1
#> [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#> [39] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#> [77] 0 0 0 0 0
#>
#> $V2
#> [1] 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0
#> [39] 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 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1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
#> [39] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
#> [77] 1 1 1 1 1
创建于 2022 年 9 月 30 日 reprex v2.0.2
关于r - 有条件地改变值并寻找组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73904204/