Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用R查找适合特定范围(每个人)的列并添加1,否则添加0_R_Range_Multiple Columns - Fatal编程技术网

如何使用R查找适合特定范围(每个人)的列并添加1,否则添加0

如何使用R查找适合特定范围(每个人)的列并添加1,否则添加0,r,range,multiple-columns,R,Range,Multiple Columns,我有一个数据框,有三个初始列:ID、开始和结束位置。其余的列是数字染色体位置,看起来如下: ID start end 1 2 3 4 5 6 7 ... n ind1 2 4 ind2 1 3 ind3 5 7 ID start end 1 2 3 4 5 6 7 ... n ind1 2 4 0 1 1 1 0 0 0 ... 0 ind2 1 3 1

我有一个数据框,有三个初始列:ID、开始和结束位置。其余的列是数字染色体位置,看起来如下:

ID   start  end  1  2  3  4  5  6  7  ...  n
ind1  2      4   
ind2  1      3
ind3  5      7
ID   start  end  1  2  3  4  5  6  7  ...  n
ind1  2      4   0  1  1  1  0  0  0  ...  0 
ind2  1      3   1  1  1  0  0  0  0  ...  0 
ind3  5      7   0  0  0  0  1  1  1  ...  1
我想要的是根据每个个体的范围(开始:结束)填写空列(1:n)。例如,在第一个个体(ind1)中,范围从位置2到4,然后用一(1)填充符合范围的位置,用零(0)填充超出范围的位置。为了简化,所需的输出应如下所示:

ID   start  end  1  2  3  4  5  6  7  ...  n
ind1  2      4   
ind2  1      3
ind3  5      7
ID   start  end  1  2  3  4  5  6  7  ...  n
ind1  2      4   0  1  1  1  0  0  0  ...  0 
ind2  1      3   1  1  1  0  0  0  0  ...  0 
ind3  5      7   0  0  0  0  1  1  1  ...  1

我将非常感谢您的评论。

如果您从数据框
df
开始,而没有添加列

你可以

mx <- max(df[-1])
M <- Map(function(x, y) replace(integer(mx), x:y, 1L), df$start, df$end)
cbind(df, do.call(rbind, M))
#     ID start end 1 2 3 4 5 6 7
# 1 ind1     2   4 0 1 1 1 0 0 0
# 2 ind2     1   3 1 1 1 0 0 0 0
# 3 ind3     5   7 0 0 0 0 1 1 1

假设您知道可以从
数据中使用
between
函数的列数。表
包:

cols <- paste0('c',1:7)

library(data.table)
setDT(DF)[, (cols) := lapply(1:7, function(x) +(between(x, start, end)))][]
注:

  • 最好不要仅仅用数字来命名你的列。因此,我在列名称的开头添加了一个
    c
  • +(x,start,end)之间使用
    +
    是一种语法。更惯用的方法是使用
    作为.integer(介于(x,start,end)之间)

使用数据:

DF <- read.table(text="ID   start  end
ind1  2      4   
ind2  1      3
ind3  5      7", header=TRUE)

DF谢谢!,它工作得很好,唯一的额外事情是确保开始和结束值与cols顺序一致。很好的base R解决方案!
DF <- read.table(text="ID   start  end
ind1  2      4   
ind2  1      3
ind3  5      7", header=TRUE)