【问题标题】:Add 0 or 1 in a df depending on conditions from another df [duplicate]根据另一个df的条件在df中添加0或1 [重复]
【发布时间】:2017-11-16 21:07:10
【问题描述】:

我有一个数据框 df1

file_name  loc
rep1   chr1:62161618:62162663:-
rep2   chr1:62161618:62162669:-
...

然后我生成一个空矩阵 (df2),其中 file_name 作为行,loc 作为列。我想在df1 中的每个位置添加“1”值。举个例子:

     chr1:62161618:62162663:-    chr1:62161618:62162669:-...
rep1           1                            0
rep2           0                            1
...

有什么建议吗? 谢谢!

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    使用dplyrtidyr 的解决方案。

    library(dplyr)
    library(tidyr)
    
    dt2 <- dt %>%
      mutate(condition = 1) %>%
      spread(loc, condition, fill = 0)
    dt2
    #   file_name chr1:62161618:62162663:- chr1:62161618:62162669:-
    # 1      rep1                        1                        0
    # 2      rep2                        0                        1
    

    数据

    dt <- read.table(text = "file_name  loc
    rep1   'chr1:62161618:62162663:-'
                     rep2   'chr1:62161618:62162669:-'",
                     header = TRUE, stringsAsFactors = FALSE)
    

    【讨论】:

    • 嗨!感谢您的反馈!我想知道代码是否会有所不同,而不是 0 和 1,我将使用带有 df1 中的值的第三列来填充 df2
    • 我认为您可能需要一个连接操作。您可能想问一个新问题。
    猜你喜欢
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 2020-04-06
    • 2020-06-09
    相关资源
    最近更新 更多