将数据表中的单个值分解为值为1的行

问题描述投票：1回答：2

``````set.seed(135813) # whimsical seed
id_dt <- data.table(id = 1:6) # Six "id" numbers
duration_dt <- data.table(duration = abs(rnorm(6, mean = 20, sd = 10))) # Sample of six arbitrary positive values
id_durs <- id_dt[, .(id = id, duration = round(duration_dt\$duration))] # combine the above DTs; round values to ints
``````

``````    id    duration
--    --------
1       7
2      34
3      33
4       2
5      40
6      27
``````

``````    id    duration    count
--    --------    -----
1       7          1
1       7          1
1       7          1
1       7          1
1       7          1
1       7          1
1       7          1      <== duration = 7, Rows = 7
2      34          1
2      34          1
2      34          1
2      34          1
2      34          1
2      34          1
2      34          1
2      34          1
...    ...        ...     <== duration = 34, Rows = 34
3      33          1
...    ...        ...     <== duration = 33, Rows = 33
4       2          1
4       2          1     <== duration = 2, Rows = 2
5      40          1
...    ...        ...     <== duration = 40, Rows = 40
6      27          1
...    ...        ...     <== duration = 27, Rows = 27
``````

``````stuff = 50.4
decomp <- lapply(1:round(stuff), function(i) i <- 1)
result <- data.table(count = unlist(decomp))
``````

``````for (i in 1:length(id_durs))
{
id_dur_val <- data.table(id = id_durs\$id,
duration = id_durs\$duration,
count = rep(1, each = id_durs\$duration[i]))
}
``````

r
2个回答
0

``````library(data.table)

id_durs[, count := 1][rep(id, duration), ]
#>      id duration count
#>   1:  1        7     1
#>   2:  1        7     1
#>   3:  1        7     1
#>   4:  1        7     1
#>   5:  1        7     1
#>  ---
#> 139:  6       27     1
#> 140:  6       27     1
#> 141:  6       27     1
#> 142:  6       27     1
#> 143:  6       27     1
``````

0

``````  duration_dt[,.(count = rep(numeric(.N) + 1, duration)), by = duration]

duration count
1:        7     1
2:        7     1
3:        7     1
4:        7     1
5:        7     1
---
139:       27     1
140:       27     1
141:       27     1
142:       27     1
143:       27     1
``````