r - 将具有间隔的单行转换为等于间隔的多行

标签 r dataframe rows

假设你有这样的事情:

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/

相关文章:

r - 如何清除错误 : object <some function> is not exported by 'namespace:<some package>' which shows up when building my R package?

php - 使用php和Mysql按最大数量排序并确认

MySQL 选择值在其他行中有多个值的位置

r - 将循环输出存储在 R 中的数据帧中

R : ggplot2 : facet_grid : how include math expressions in few (not all) labels?

r - 如何在环境中使用数据表的集合函数

python - rpy2 转换矩阵 -> DataFrame

Python-替换数据框中的字符串

r - 交易从长到宽 reshape ,加入买卖数据帧

java - 如何保留选定的行并从 jtable 中删除其他行?