按指定数量重复 df 列中的值,并将整数计数连接到重复值

标签 r dataframe seq rep

我想使用 R 从 template_df 创建一个 expanded_df,其中每行重复 中单独列中指定的次数>template_df,并且整数计数连接到 expanded_df 中的 ID 列,指定此行在 expanded_df 中重复的数字。

我希望每个 ID 类别的计数从 600 开始。

例如,template_df:

Initial_ID  Count
a           2
b           3
c           1
d           4

expanded_df:

Expanded_ID
a-600
a-601
b-600
b-601
b-602
c-600
d-600
d-601
d-602
d-603

大家有什么想法吗?谢谢!

最佳答案

我们可以使用uncount来展开行,然后获取rowid('Initial_ID'的)在添加599后粘贴

library(dplyr)
library(tidyr)
library(data.table)
library(stringr)
template_df %>% 
   uncount(Count) %>% 
   transmute(Expanded_ID = str_c(Initial_ID, 599 + rowid(Initial_ID), sep = '-'))

-输出

 Expanded_ID
1        a-600
2        a-601
3        b-600
4        b-601
5        b-602
6        c-600
7        d-600
8        d-601
9        d-602
10       d-603

或者将base Rreppaste结合使用

data.frame(Expanded_ID = with(template_df, paste0(rep(Initial_ID, Count), "-", 
       599 + sequence(Count))))

-输出

   Expanded_ID
1        a-600
2        a-601
3        b-600
4        b-601
5        b-602
6        c-600
7        d-600
8        d-601
9        d-602
10       d-603

数据

template_df <- structure(list(Initial_ID = c("a", "b", "c", "d"), Count = c(2L, 
3L, 1L, 4L)), class = "data.frame", row.names = c(NA, -4L))

关于按指定数量重复 df 列中的值,并将整数计数连接到重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71443831/

相关文章:

python - 绘制 dataFrame 中所有值的直方图

r - R中数据帧的条件总和

python - 如何在 Pandas 数据框中用 0 填充多个列表?

zsh - (zsh 大括号扩展 | seq) 用于字符列表 - 如何?

R dplyr::使用字符串变量重命名并选择

r - 根据组内的特定行在 group_by 内进行变异

r - 查找没有任何包的基因组组合

scala - 组合序列的惯用 Scala 解决方案

performance - 加速嵌套循环;可以向量化吗?

r - 选择线图中多个误差线的方向