假设你有类似的东西:
sudo chmod 755 -R your_folder
我想通过将间隔分成单独的行来扩展行,所以:
Col1 Col2
a odd from 1 to 9
b even from 2 to 14
c even from 30 to 50
...
请注意,当它说“偶数”时,下限和上限也是偶数,奇数也是如此。
答案 0 :(得分:4)
将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
可重现形式的输入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")
tidyr的下一个版本支持into
向量中的NA来表示要忽略的字段,因此可以写出上面的separate
语句:
separate(Col2, into = c("parity", NA, "from", NA, "to")) %>%
答案 1 :(得分:1)
tidyverse
:
library(tidyverse)
df %>% mutate(Col2 = map(str_split(Col2," "),
~seq(as.numeric(.[3]),as.numeric(.[5]),2))) %>%
unnest
或者可能更具可读性,从@ g-grothendieck的解决方案中借用separate
:
df %>%
separate(Col2,as.character(1:5),convert=TRUE) %>%
transmute(Col1,Col2 = map2(`3`,`5`,seq,2)) %>%
unnest
答案 2 :(得分:1)
以下是使用base R
的选项。我们使用gregexpr/regmatches
将{Col2'中的数字元素提取到list
,然后将seq
和stack
的元素序列提取到data.frame
}
res <- stack(setNames(lapply(regmatches(DF$Col2, gregexpr("\\d+", DF$Col2)), function(x)
seq(as.numeric(x[1]), as.numeric(x[2]), by = 2)), DF$Col1))[2:1]
colnames(res) <- colnames(DF)
head(res)
# Col1 Col2
#1 a 1
#2 a 3
#3 a 5
#4 a 7
#5 a 9
#6 b 2