【发布时间】:2014-01-13 09:34:50
【问题描述】:
给定一个 data.frame,其中 start 和 end 代表范围。
id start end
1 3 51
2 20 28
如果范围包含另一个数字或数字序列并将它们分组,例如按 25,我正在尝试将行拆分为多行
id start end splitGroup
1 3 25 0
1 25 51 25
2 20 25 0
2 25 28 25
这里的功能类似于使用 plyr 包按常规序列进行拆分
df <- data.frame(
id = c(1:2),
start = c(3,20),
end = c(51,28)
)
splitBy <- 20
rowSplit <- function(df, splitBy){
newDf <- ddply(df, .(id), function(x){
data.frame(
id = x$id,
start = x$start,
end = x$end,
splitGroup = seq(
floor(x$start/splitBy)*splitBy,
floor(x$end/splitBy)*splitBy,
by=splitBy
)
)
})
newDf <- within(newDf, {
start <- ifelse(
floor(start/splitBy)*splitBy == splitGroup,
start,
splitGroup
)
end <- ifelse(
end < (splitGroup + splitBy),
end,
(splitGroup + splitBy)
)
})
return(newDf)
}
rowSplit(df, splitBy)
id start end splitGroup
1 3 20 0
1 20 40 20
1 40 51 40
2 20 28 20
如何使用任何单个数字或一组不规则的数字来做到这一点
【问题讨论】: