gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:24:35 25 4
gpt4 key购买 nike

假设你有这样的事情:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com