r - 旋转更长的多列,同时旋转更宽的其他列
问题描述
您好,我有一个每组 3-5 行的数据集,如下所示,我想以更长的格式放置一些列,并以更宽的格式放置列。
下面的第一个数据集代表原始格式,我想将其转换为第二个。我使用了 pivot更宽的 cols = c("Jan", "Feb") 但我无法同时将 Type 列旋转得更长。
data <- as.data.frame(matrix(ncol=5, nrow=6))
colnames(data) <- c("names", "group", "Type", "Jan", "Feb")
data$names <- c("P1", "P1", "P1", "P2", "P2", "P2")
data$group <- "S"
data$Type <- c("Beg", "Middle", "End", "Beg", "Middle", "End")
data$Jan <- c(1, 2, 3, 10, 5, 15)
data$Feb <- c(5, 5, 10, 5, 2, 7)
names group Type Jan Feb
1 P1 S Beg 1 5
2 P1 S Middle 2 5
3 P1 S End 3 10
4 P2 S Beg 10 5
5 P2 S Middle 5 2
6 P2 S End 15 7
data_transformed <- as.data.frame(matrix(ncol=6, nrow=4))
colnames(data_transformed) <- c("names", "group", "Month", "Beg", "Middle", "End")
data_transformed$names <- c("P1", "P1", "P2", "P2")
data_transformed$group <- "S"
data_transformed$Month <- c("Jan", "Feb")
data_transformed$Beg <- c(1, 10, 5, 5)
data_transformed$Middle <- c(2, 5, 5, 2)
data_transformed$End <- c(2, 15, 10, 7)
names group Month Beg Middle End
1 P1 S Jan 1 2 2
2 P1 S Feb 10 5 15
3 P2 S Jan 5 5 10
4 P2 S Feb 5 2 7
解决方案
在这里,我们需要一个pivot_longer
+pivot_wider
即首先将 s 重塑为“long”,将col
s重塑Jan
为“Feb”,然后使用“Type”中的列名将 long 重塑为更宽的格式
library(dplyr)
library(tidyr)
data %>%
pivot_longer(cols = Jan:Feb, names_to = 'Month') %>%
pivot_wider(names_from = Type, values_from = value)
-输出
# A tibble: 4 x 6
# names group Month Beg Middle End
# <chr> <chr> <chr> <dbl> <dbl> <dbl>
#1 P1 S Jan 1 2 3
#2 P1 S Feb 5 5 10
#3 P2 S Jan 10 5 15
#4 P2 S Feb 5 2 7
或使用recast
来自reshape2
library(reshape2)
recast(data, measure = c("Jan", "Feb"),
names + group + variable ~ Type, values.var = 'value')
推荐阅读
- excel - Groupby 的 Row_Number 查询
- leaflet - 如何在传单中添加 maidengrid 叠加层
- javascript - JSX 中的 lambda 是如何工作的?
- c# - 如何创建下载文件并刷新页面
- python-3.x - 在指定存储库中打开新 PR 后,如何自动接收 PR 状态(标题、开启者等)?
- wordpress - 测试电子邮件已发送但未由 WordPress 交付
- vim - 尝试将文件类型添加到 autocmd 会产生错误
- delphi - 如何在 Delphi 2010 中运行媒体播放器时修复“初始化 MCI 时出现问题”调试消息
- c# - 为什么我的 Enum 参数回到默认值?
- c# - Owin 新项目抛出 NullReference