[英]Expanding the range into a list of consecutive numbers in a table in R
這是我的ID為A,B和B列的表格的示例:
ID A B
5 1 758
5 1 560
50 500 8156
我想將其轉換為具有相同ID的表中的連續數字列表(遞增1+)。 這是我想要的表格示例:
ID Position
5 1, 2, 3 ... 758
50 500, 501, 502 ... 8156
我已經在seq(...)中的R表中嘗試了此操作,並且使用了冒號功能,但是我收到了相同的警告消息,如下所示:
警告消息:1:在x6 $ S1:x6 $ E1中:數值表達式具有281個元素:僅第一個使用
有誰知道解決這個問題的方法嗎? 我已經可以用perl中的數組來做到這一點,但是我無法保留ID。
干杯,
丹尼爾
使用dplyr
您可以執行以下操作:
library("dplyr")
DF
# ID A B
#1 5 1 758
#2 5 1 560
#3 50 500 8156
summaryDF = DF %>%
group_by(ID) %>%
summarise(minPos = min(A),maxPos = max(B)) %>%
as.data.frame()
summaryDF
# ID minPos maxPos
#1 5 1 758
#2 50 500 8156
#you can modify step here, have chosen large step for ease in output
step = 750
#For each ID, we create a seq from minPos to maxPos and using paste0
#to collapse into one string
customFun = function(x) {
data.frame(ID=x$ID,minPos=x$minPos,maxPos=x$maxPos,Position=paste0(seq(x$minPos,x$maxPos,step),collapse=","),stringsAsFactors = FALSE)
}
summaryDF = summaryDF %>%
group_by(ID) %>%
do(customFun(.)) %>%
as.data.frame()
輸出:
summaryDF
# ID minPos maxPos Position
#1 5 1 758 1,751
#2 50 500 8156 500,1250,2000,2750,3500,4250,5000,5750,6500,7250,8000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.