我有一个数据框如下。
> df
condition duration start end
1 A 2 3 4
2 B 3 8 10
3 A 2 7 8
我想将数据框转换为一个表格,该表格为每个条件的每个位置提供 0 或 1。条件可以在开始和结束处重叠并出现多次;但是,一种情况的多次出现不会。
它应该看起来像下面这样
> df2
count A B
1 1 0 0
2 2 0 0
3 3 1 0
4 4 1 0
5 5 0 0
6 6 0 0
7 7 1 0
8 8 1 1
9 9 0 1
10 10 0 1
最佳答案
library(dplyr); library(tidyr)
df |>
uncount(duration, .id = "copy") |>
mutate(row = start + copy - 1) |>
count(condition, row) |>
complete(condition, row = 1:max(row), fill = list(n = 0)) |>
pivot_wider(names_from = condition, values_from = n)
结果
# A tibble: 10 × 3
row A B
<dbl> <int> <int>
1 1 0 0
2 2 0 0
3 3 1 0
4 4 1 0
5 5 0 0
6 6 0 0
7 7 1 0
8 8 1 1
9 9 0 1
10 10 0 1
关于r - 按列开始和结束转换数据帧 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75003077/