Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.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 如何将一个ID的最后一个值添加到下一个ID的值中_R_Bioinformatics - Fatal编程技术网

R 如何将一个ID的最后一个值添加到下一个ID的值中

R 如何将一个ID的最后一个值添加到下一个ID的值中,r,bioinformatics,R,Bioinformatics,这个问题应该很简单,但我不知道如何在R中实现。基本上,我有一个两列文件,其中第一列表示scaffold id,第二列表示SNP在特定scaffold中的位置 id POS 0001 38 0001 46 0001 50 0002 17 0002 23 0002 46 0003 13 0003 19 0003 38 ... ... 我想创建一个新的列,其中第一个脚手架的SNP位置new_POS是相同的,但对于第二个脚手架以及之后的新_POS将是将前一个脚手架的最后一个

这个问题应该很简单,但我不知道如何在R中实现。基本上,我有一个两列文件,其中第一列表示scaffold id,第二列表示SNP在特定scaffold中的位置

id    POS
0001  38
0001  46
0001  50
0002  17
0002  23
0002  46
0003  13
0003  19
0003  38
...   ...
我想创建一个新的列,其中第一个脚手架的SNP位置new_POS是相同的,但对于第二个脚手架以及之后的新_POS将是将前一个脚手架的最后一个POS值添加到第二个脚手架的每个POS中的结果,即50+17、50+23、50+46,。。。。对于第三个脚手架96+13,96+19,96+38。。。等等正如你在这里看到的:

id    POS  NEW_POS
0001  38   38
0001  46   46
0001  50   50
0002  17   67
0002  23   73
0002  46   96
0003  13   109
0003  19   115
0003  38   134
...   ...  ...
下面是一个使用lag和cumsum的解决方案:

数据:

> dput(df1)
structure(list(id = c("0001", "0001", "0001", "0002", "0002", 
"0002", "0003", "0003", "0003"), POS = c(38, 46, 50, 17, 23, 
46, 13, 19, 38)), .Names = c("id", "POS"), class = "data.frame", row.names = c(NA, 
-9L))
下面是一个使用lag和cumsum的解决方案:

数据:

> dput(df1)
structure(list(id = c("0001", "0001", "0001", "0002", "0002", 
"0002", "0003", "0003", "0003"), POS = c(38, 46, 50, 17, 23, 
46, 13, 19, 38)), .Names = c("id", "POS"), class = "data.frame", row.names = c(NA, 
-9L))
这是一个data.table解决方案,它也使用shift和cumsum,但在连接时更新

返回

     id POS NEW_POS
1: 0001  38      38
2: 0001  46      46
3: 0001  50      50
4: 0002  17      67
5: 0002  23      73
6: 0002  46      96
7: 0003  13     109
8: 0003  19     115
9: 0003  38     134
解释 从而创建新的位置

数据 这是一个data.table解决方案,它也使用shift和cumsum,但在连接时更新

返回

     id POS NEW_POS
1: 0001  38      38
2: 0001  46      46
3: 0001  50      50
4: 0002  17      67
5: 0002  23      73
6: 0002  46      96
7: 0003  13     109
8: 0003  19     115
9: 0003  38     134
解释 从而创建新的位置

数据
tmp <- DT[, last(POS), id][, .(id, shift(cumsum(V1), fill = 0))][]
tmp
#     id V2
#1: 0001  0
#2: 0002 50
#3: 0003 96
DT[tmp, on = "id", NEW_POS := POS + V2][]
DT <- structure(list(id = c("0001", "0001", "0001", "0002", "0002", 
"0002", "0003", "0003", "0003"), POS = c(38L, 46L, 50L, 17L, 
23L, 46L, 13L, 19L, 38L)), .Names = c("id", "POS"), row.names = c(NA, 
-9L), class = "data.frame")
#coerce to data.table
setDT(DT)