【问题标题】:substitute value in one matrix based on condition in another matrix根据另一个矩阵中的条件替换一个矩阵中的值
【发布时间】:2014-11-13 03:30:45
【问题描述】:

这是一道 R 题。

我有两个矩阵,“y”和“l”:

> head(y)
    SNP Category
1 29351  exclude
2 29357  exclude
3 29360  exclude
4 29372  include
5 29426  include
6 29432  include

> head(l)
  start  stop
1   246 11012
2 11494 13979
3 14309 18422
4 20728 20995
5 21457 29345
6 30035 31693

如果矩阵 y 中的一行在第二列中具有值“包含”,我想检查矩阵 y 中第一列中的对应值是否位于矩阵中的“开始”和“停止”值之上或之间l.如果矩阵 y 中的值确实位于矩阵 l 中的值之上或之间,则在矩阵 y 中将值“包含”替换为“排除”。我想我可以使用嵌套的 for 循环来做到这一点,但想知道一种更优雅、更快的方法。矩阵的长度不等。谢谢你。

【问题讨论】:

  • 我可能会考虑像here 建议的那样进行合并

标签: r dataframe


【解决方案1】:

这行得通,但速度很慢。

y <- read.csv(file="SNP_pos_categorised0.99cutoff.csv", header=T)
l <- read.csv("SNPsToMoveFromINCLUDEtoEXCLUDE.csv", header=T)

colnames(y)
#[1] "SNP"      "Category"

levels(y$Category)
#[1] " exclude" " include"

colnames(l)
#[1] "start" "stop"

#start processing
for(i in 1:nrow(y))
{
    if(y[i,"Category"]==" include")
    {
        for(j in 1:nrow(l))
        {
            if(y[i,"SNP"] >= l[j,"start"] & y[i,"SNP"]<= l[j,"stop"])
            {
                y[i, "Category"] <- replace(y[i,"Category"], y[i,"Category"]==" include", " exclude" )
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 2016-09-10
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多