【问题标题】:How to convert a data frame into binary numbers (1's and 0's)?如何将数据帧转换为二进制数(1 和 0)?
【发布时间】:2021-05-26 17:38:43
【问题描述】:

所以我有一些基因表达计数数据,列包含我的所有样本,每行包含约 60000 个基因。我已将数据转换为 TPM,我想排除低于 TPM 阈值 5 的某些基因。为此,我需要使用 df[df > 5] <- 1 将 TPM 值 > 5 转换为 1,但还将 TPM 值

Gene       Sample A  Sample B          Gene       Sample A  Sample B
Gene 1      10.23     11.20            Gene 1        1        1
Gene 2       2.89      6.76            Gene 2        0        1
Gene 3       9.66      4.34            Gene 3        1        0
...                                    ...

【问题讨论】:

  • 可以分享输入表的例子吗?但是根据您的描述,我认为一个简单的ifelse 可以工作吗? df$column_name = ifelse(df$column_name > 5, 1, ifelse(df$column_name < 5, 0, df$column_name)

标签: r


【解决方案1】:

这行得通吗:

data.frame(cbind(df[1],apply(df[-1],2,function(x) +(x > 5))))
    gene SampleA SampleB
1 Gene 1       1       1
2 Gene 2       0       1
3 Gene 3       1       0

【讨论】:

    【解决方案2】:

    一个整洁的选项。

    library(dplyr)
    
    mutate(df, across(-Gene, ~ + (. > 5)))
    
    # # A tibble: 3 x 3
    #   Gene   `Sample A` `Sample B`
    #   <chr>       <int>      <int>
    # 1 Gene 1          1          1
    # 2 Gene 2          0          1
    # 3 Gene 3          1          0
    

    数据

    df <- structure(list(Gene = c("Gene 1", "Gene 2", "Gene 3"), `Sample A` = c(10.23, 
    2.89, 9.66), `Sample B` = c(11.2, 6.76, 4.34)), row.names = c(NA, 
    -3L), class = c("tbl_df", "tbl", "data.frame"))
    

    【讨论】:

      猜你喜欢
      • 2013-01-09
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 2023-03-18
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 2021-08-05
      相关资源
      最近更新 更多