If anyone good at R programming please help me with the below scenario
R dataframe 1 :
Index | Powervalue |
---|---|
0 | 1 |
1 | 2 |
2 | 4 |
3 | 8 |
4 | 16 |
5 | 32 |
R dataframe 2 :
CombinedValue |
---|
20 |
50 |
Expected Final Result :
CombinedValue | possiblecodes |
---|---|
20 | 4, 16 |
50 | 2, 16, 32 |
This is little urgent for me. Thanks in advance.
Can some one help with this.
CodePudding user response:
Here you go.
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
df is now:
sum values
1 50 32, 16, 2
2 20 16, 4
3 6 4, 2