假设你有这样的事情:
Col1 Col2
a odd from 1 to 9
b even from 2 to 14
c even from 30 to 50
...
我想通过将间隔分成单独的行来扩展行,所以:
Col1 Col2
a 1
a 3
a 5
...
b 2
b 4
b 6
...
c 30
c 32
c 34
...
注意,当它说“even from”时,上下界也是偶数,奇数也是如此。
最佳答案
将 Col2 分成单独的列,然后为每一行创建序列:
library(dplyr)
library(tidyr)
DF %>%
separate(Col2, into = c("parity", "X1", "from", "X2", "to")) %>%
group_by(Col1) %>%
do(data.frame(Col2 = seq(.$from, .$to, 2))) %>%
ungroup
注1
假定可重现形式的输入 DF
为:
DF <- structure(list(Col1 = c("a", "b", "c"), Col2 = c("odd from 1 to 9",
"even from 2 to 14", "even from 30 to 50")), .Names = c("Col1",
"Col2"), row.names = c(NA, -3L), class = "data.frame")
注2
tidyr 的下一个版本在 into
向量中支持 NA 以表示要忽略的字段,因此可以编写上面的 separate
语句:
separate(Col2, into = c("parity", NA, "from", NA, "to")) %>%
关于r - 将具有间隔的单行转换为等于间隔的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48707294/