我正在使用一个名为“data_1”的表,其中一列“col_1”具有二进制数据类型(例如,1100000)。
我想从该列获取所有“1”的位置(索引)并将它们存储在另外 1 列或更多列中。
输出可以是:
1) 'col_2' 存储值 6 和 7,表示索引 6 和 7 处有 '1'。
2) 或者我们可以将输出存储在多个列 'pos_1', 'pos_2', 'pos_3', 'pos_4', 'pos_5', 'pos_6', 'pos_7' 中,值为 (0, 0, 0, 0 , 0, 1, 1),表示索引 6 和 7 处有“1”,其余位置为“0”。
我们如何在mysql或R中实现?
我已经尝试过:
在 R 中,我尝试了将以下函数应用于“col_1”,但它不起作用。
convert_to_binary <- function(n) {
if(n > 1) {
convert_to_binary(as.integer(n/2))
}
cat(n %% 2)
}
data_1$col_2 <- convert_to_binary(data_1$col_1)
在 MySQL 中,以下仅返回第一个“1”
select POSITION(1 IN col_1) as col_2 from data_1;
这里有什么建议吗?
谢谢!
最佳答案
这是 R 中的解决方案:
col_1<-c(1100000, 1100001, 1100100)
data_1 <- data.frame(col_1)
as.character(data_1$col_1) -> data_1$col_1
position<-function(x){unlist(gregexpr(pattern ='1',x))}
data_1$col_2 <- sapply(data_1$col_1, function(x) position(x))
as.character(data_1$col_2) -> data_1$col_2
gsub(":", ",", data_1$col_2) -> data_1$col_2
gsub("c", "", data_1$col_2) -> data_1$col_2
希望对你有帮助
关于mysql - SQL 或 R : Find and display the index of all '1' s from a column with binary data type and store in another 1 or more columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56192145/