![](/img/trans.png)
[英]Finding all sum of 2 power value combination values of a given number in R
[英]Finding all sum of 2 power value combination values of a given number in R
R数据框1:
指数 | 力值 |
---|---|
0 | 1个 |
1个 | 2个 |
2个 | 4个 |
3个 | 8个 |
4个 | 16 |
5个 | 32 |
R 数据框 2:
合并值 |
---|
20 |
50 |
预期最终结果:
我们可以得到图像中的输出吗? 如果是,请帮助。
下面的代码提供了 stackoverflow mate 之一。 我正在寻找如何将值分隔为 1 和 0 的列。
df <- data.frame(sum = c(50, 20, 6))
values_list <- list()
for (i in 1:nrow(df)) {
sum <- df$sum[i]
values <- c()
while (sum > 0) {
value <- 2^floor(log2(sum))
values <- c(values, value)
sum <- sum - value
}
values_list[[i]] <- values
}
df$values <- values_list
我们可以将列固定到 31 次幂,如附图所示。 这些列与可能的代码匹配,然后为其余列放置 1 和 0,否则为 0。 请帮忙。
这是一个输出与预期输出匹配的函数。
toCodes <- function(x) {
n <- floor(log2(x))
pow <- rev(seq.int(max(n)))
# 'y' is the matrix of codes
y <- t(sapply(x, \(.x) (.x %/% 2^pow) %% 2L))
i_cols <- apply(y, 2, \(.y) any(.y != 0L))
colnames(y) <- sprintf("code_%d", 2^pow)
#
possiblecodes <- apply(y, 1, \(p) {
codes <- 2^pow[as.logical(p)]
paste(rev(codes), collapse = ",")
})
data.frame(combinedvalue = x, possiblecodes, y[, i_cols])
}
x <- c(20L, 50L)
toCodes(x)
#> combinedvalue possiblecodes code_32 code_16 code_4 code_2
#> 1 20 4,16 0 1 1 0
#> 2 50 2,16,32 1 1 0 1
创建于 2022-12-19,使用reprex v2.0.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.