按 R 中的列值排序 table 行

Sort table rows by column values in R

我有一个 BLAST 工具的经典输出,它就像下面的 table。为了使 table 更易于阅读,我减少了列数。

query subject startinsubject endinsubject
1 SRR 50 100
1 SRR 500 450

我需要创建另一列,称为“strand”,当查询像第一行一样向前时,因此 startinsubject 小于 endinsubject,写入新列 F。 另一方面,当查询反向时,如第二行,其中 startinsubject 高于 endinsubject,它会在新的“strand”列中添加一个 R。

我想要一个新的 table,如下图所示。谁能帮帮我?一千个感谢

query subject startinsubject endinsubject strand
1 SRR 50 100 F
1 SRR 500 450 R

我们可以使用 ifelse/case_when 或者只是将逻辑索引转换为数字索引以进行替换

library(dplyr)
df1 <- df1 %>% 
   mutate(strand =  c("R", "F")[1 + (startinsubject < endinsubject)])

-输出

df1
 query subject startinsubject endinsubject strand
1     1     SRR             50          100      F
2     1     SRR            500          450      R

数据

df1 <- structure(list(query = c(1L, 1L), subject = c("SRR", "SRR"), 
    startinsubject = c(50L, 500L), endinsubject = c(100L, 450L
    )), class = "data.frame", row.names = c(NA, -2L))

这是一个ifelse选项。您可以使用以下代码:

df <- data.frame(query = c(1,1),
                 subject = c("SRR", "SRR"),
                 startinsubject = c(50, 500),
                 endinsubject = c(100, 450))

library(dplyr)

df %>%
  mutate(strand = ifelse(startinsubject > endinsubject, "R", "F"))

输出:

  query subject startinsubject endinsubject strand
1     1     SRR             50          100      F
2     1     SRR            500          450      R