我们可以使用来自
tidyverse
:
首先,我们按天分组,然后计算
Value
.我们使用
row_number
,因为它将导致跨行的唯一排序。我们使用
unite
创建
reason
列,然后使用
gather
,
团结
和
spread
做最后宽到长到宽的转换。需要注意的一点是
value_*
列仍然被编码为字符值,这很容易更改。
dat %>%
group_by(Day) %>%
mutate(row_num_value = row_number(Value)) %>%
unite(reason, Col1, Another, sep = " - ") %>%
gather(variable, value, reason, Value) %>%
unite(variable2, variable, row_num_value, sep = '_') %>%
spread(variable2, value)
Day High.Low reason_1 reason_2 reason_3 Value_1 Value_2 Value_3
<chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 2018-01-01 High A - B B - G NA 20 30 NA
2 2018-01-02 Low C - D C - G C - M 40 50 70