tst <- data.frame(ID = c(123, 123, 123, 124, 124, 124),
Identifier = c("S2", "S2", "S5", "S3", "S2", "S2"),
Speed = c(15,24,11,34,13,15),
Box_loc = c(801,802,803,801,802,803),
Ord = c(86,87,90,81,82,84))
Run Code Online (Sandbox Code Playgroud)
我一直在尝试将上述数据从长格式转换为宽格式,但是每当我尝试自己研究它时,数据看起来都不够相似以至于我无法正确翻译它。看起来它应该是一个简单的解决方案,但也许我遗漏了一些关键细节。
| ID | 标识符(801) | 速度(801) | 订单(801) | 标识符(802) | 速度(802) | 订单(802) | 标识符(803) | 速度(803) | 订单(803) |
|---|---|---|---|---|---|---|---|---|---|
| 123 | S2 | 15 | 86 | S2 | 24 | 87 | S5 | 11 | 90 |
| 124 | S3 | 34 | 81 | S2 | 13 | 82 | S2 | 15 | 84 |
我想让我的数据看起来像这张表。实际数据有不止 2 个 ID(如果重要的话),标题中的数字是 Box_loc。换句话说,对于每个 Box_loc,都有 123-250 的 ID,每个 ID 都需要自己的行和这些列。我的实际文件有 10 列左右,但语法应该大致相同。
您可以使用以下解决方案:
library(tidyr)
tst %>%
pivot_wider(names_from = Box_loc,
values_from = !c(ID, Box_loc),
names_glue = "{.value}({Box_loc})")
# A tibble: 2 x 10
ID `Identifier(801)` `Identifier(802)` `Identifier(803)` `Speed(801)` `Speed(802)`
<dbl> <chr> <chr> <chr> <dbl> <dbl>
1 123 S2 S2 S5 15 24
2 124 S3 S2 S2 34 13
# ... with 4 more variables: Speed(803) <dbl>, Ord(801) <dbl>, Ord(802) <dbl>, Ord(803) <dbl>
Run Code Online (Sandbox Code Playgroud)