我在重塑以下数据框时遇到麻烦:
set.seed(45)
dat1 <- data.frame(
name = rep(c("firstID", "secondID"), each=4),
numbers = rep(1:4, 2),
value = rnorm(8),
Category = rep(c("111", "22"), each=4)
)
dat1
ID Timestamp value Category
1 firstID 1 0.3407997 111
2 firstID 2 -0.7033403 111
3 firstID 3 -0.3795377 111
4 firstID 4 -0.7460474 111
5 secondID 1 -0.8981073 22
6 secondID 2 -0.3347941 22
7 secondID 3 -0.5013782 22
8 secondID 4 -0.1745357 22
我似乎无法弄清楚如何获得以下结果:
firstID secondID
111 22
0.3407997 -0.8981073
-0.7033403 -0.3347941
-0.3795377 -0.5013782
-0.7460474 -0.1745357
答案 0 :(得分:2)
下面不是宽格式的最终输出应该是什么?
library(tidyverse)
dat1 %>%
pivot_wider(
id_cols = numbers,
names_from = c(name, Category),
values_from = value
) %>%
select(-numbers)
## A tibble: 4 x 2
# firstID_111 secondID_22
# <dbl> <dbl>
#1 0.341 -0.898
#2 -0.703 -0.335
#3 -0.380 -0.501
#4 -0.746 -0.175