【发布时间】:2022-01-20 03:18:36
【问题描述】:
我想将一个数据集从长转换为宽。 数据包含每个时间点的多个观测值。
为了说明,请考虑以下两个示例。
在下面的示例 1 中,数据不包含多个观察结果,并且可以从长转换为宽。
在下面的示例 2 中,数据确实包含多个观察结果(每个时间点 n=3)并且无法从长转换为宽,使用 dcast 和 pivot_wider 进行测试。 p>
谁能建议一种将示例 2 中的测试数据转换为有效格式的方法?
重现问题的代码:
library(ggplot2)
library(ggcorrplot)
library(reshape2)
library(tidyr)
library(data.table)
# EXAMPLE 1 (does work)
# Test data
set.seed(5)
time <- rep(c(0,10), 1, each = 2)
feature <- rep(c("feat1", "feat2"), 2)
values <- runif(4, min=0, max=1)
# Concatenate test data
# test has non-unique values in time column
test <- data.table(time, feature, values)
# Transform data into wide format
test_wide <- dcast(test, time ~ feature, value.var = 'values')
# EXAMPLE 2 (does not work)
# Test data
set.seed(5)
time <- rep(c(0,10), 2, each = 6)
feature <- c(rep("feat1", 12), rep("feat2", 12))
values <- runif(24, min=0, max=1)
# Concatenate test data
# test has non-unique values in time column
test <- data.table(time, feature, values)
# Transform data into wide format
test_wide <- dcast(test, time ~ feature, value.var = 'values')
警告:
Aggregate function missing, defaulting to 'length'
问题:
第一列 (time) 中的非唯一值不会被保留/允许。
# Testing with pivot_wider
test_wider <- pivot_wider(test, names_from = feature, values_from = values)
警告:
Warning message:
Values are not uniquely identified; output will contain list-cols.
问题:
第一列 (time) 中的非唯一值不会被保留/允许。
如果没有更好的主意,可能 输出可能如下所示:
| time | feat1 | feat2 |
|---|---|---|
| 0 | 0.1046501 | 0.5279600 |
| 0 | 0.7010575 | 0.8079352 |
| 0 | 0.2002145 | 0.9565001 |
等等
【问题讨论】:
-
cor(mtcars)有什么问题? -
没什么,这是一个有效的例子,也是我最终想要对测试数据做的事情。但是,我无法将测试数据转换为可用于 cor() 的格式。
-
(原始
mtcars数据集每辆车只有一个观测值。) -
我建议使用
tidy::pivot_wider,但我真的不知道您期望您的最终输出是什么。如果您专注于开始和结束数据结构并省略有关相关矩阵和mtcars的内容,您的问题会更清楚。 -
谢谢!我编辑了问题并修改了示例以使其更加清晰。我还测试了你的建议
pivot_wider,由于数据集中的多次观察,它不起作用。
标签: r dcast wide-format-data