我想使用 Rexpanded_df從 a創建一個template_df,其中每行重復在 中的單獨列中指定的次數template_df,并且整數計數連接到中的 ID 列expanded_df,指定此行的數量中重復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
誰有想法?謝謝!
uj5u.com熱心網友回復:
我們可以使用uncount擴展行,然后在添加 599 后獲取rowid'Initial_ID' 的(paste
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 R與rep和一起使用paste
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))
uj5u.com熱心網友回復:
另一種dplyr解決方案:
library(dplyr)
template_df %>%
group_by(Initial_ID) %>%
slice(rep(1:n(), each = Count)) %>%
mutate(row = 600 row_number()-1) %>%
ungroup() %>%
transmute(Expanded_ID = paste(Initial_ID,row, sep = "-"))
Expanded_ID
<chr>
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/441253.html
下一篇:替換資料框中所有出現的列
