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

标签 mysql r indexing binary

我正在使用一个名为“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/

相关文章:

mysql - 当第一种情况发生时,Sql 两个多线程唯一忽略

php - 无法向 SQL 数据库添加值

r - TMAP 上的多个层

mysql - 如何将同一个表中的两列合并为一列?

r - 矩阵不同概率的赌场游戏

algorithm - 使用第二个向量的分组对向量执行 boolean 运算

objective-c - 从字节数组创建 NSImage 的令人费解的索引错误

mysql - 使用 'Index' 还是使用查询在相关数据库列之间创建连接更好?

php - 在 Laravel 中更新 "Belongs To"关系时出现错误表

PHP/JavaScript : Javascript not sending data to PHP