我一直在寻找一个类似(但略有不同)的解决方案。张贴在这里,以防其他人有用。
在我的情况下,我需要一个更通用的解决方案,允许每个字母重复任意次数。以下是我想出了:
library(tidyverse)
df <- data.frame(letters = letters[1:4])
df
> df
letters
1 a
2 b
3 c
4 d
比方说,我想2 A的,3级B的,2周C的4 D'S:
df %>%
mutate(count = c(2, 3, 2, 4)) %>%
group_by(letters) %>%
expand(count = seq(1:count))
# A tibble: 11 x 2
# Groups: letters [4]
letters count
<fctr> <int>
1 a 1
2 a 2
3 b 1
4 b 2
5 b 3
6 c 1
7 c 2
8 d 1
9 d 2
10 d 3
11 d 4
如果你不想保持数列:
df %>%
mutate(count = c(2, 3, 2, 4)) %>%
group_by(letters) %>%
expand(count = seq(1:count)) %>%
select(letters)
# A tibble: 11 x 1
# Groups: letters [4]
letters
<fctr>
1 a
2 a
3 b
4 b
5 b
6 c
7 c
8 d
9 d
10 d
11 d
如果你想计数,以反映每个字母重复的次数:
df %>%
mutate(count = c(2, 3, 2, 4)) %>%
group_by(letters) %>%
expand(count = seq(1:count)) %>%
mutate(count = max(count))
# A tibble: 11 x 2
# Groups: letters [4]
letters count
<fctr> <dbl>
1 a 2
2 a 2
3 b 3
4 b 3
5 b 3
6 c 2
7 c 2
8 d 4
9 d 4
10 d 4
11 d 4
我能想到的唯一方法就是将数据流写入一个'do'块,然后从当前的data.frame中生成一个新的数据,就像你想要的那样('df%>%do(data.frame(column = rep 。$ column,4)))')。但是,如果data.frame有任何其他列,这充满了危险。 – r2evans
@ r2evans很棒。您可以将其作为答案发送。只需要改变'do(data.frame(a = rep(。$ a,each = 4)))'。 – Alexander