在 R 中存储数据的适当方法

数据挖掘 r 数据集 数据格式
2022-03-12 13:52:53

我有数据,如下所示:

数据表

这些数据仅适用于一个主题。我会有更多。
这些数据将在 R 中进行分析。

现在我像这样存储它们:

subject <- rep(1, times = 24)
measurement <- factor(x = rep(x = 1:3, each = 8), 
                      labels = c("Distance", "Frequency", "Energy"))
speed <- factor(x = rep(x = 1:2, each = 4, times = 3), 
                labels = c("speed1", "speed2"))
condition <- factor(x = rep(x = 1:2, each = 2, times = 6), 
                    labels = c("Control", "Experm"))
Try <- factor(x = rep(x = 1:2, times = 12), 
              labels = c("Try1", "Try2"))
result <- c(1:8, 
            11:18, 
            21:28)

dt <- data.frame(subject, measurement, speed, condition, Try, result)

将这些数据存储在 R 中(在数据框中)的适当方法是什么?

2个回答

如果没有更多信息,我只能说:

  1. 一般来说,你要存储它的说法很好
  2. 您可以根据您的用例进一步转换/存储您的数据

为了扩展#2,如果我想研究所有科目的距离与能量,那么我会像这样格式化我的数据:

> library(reshape2)
> dt2 <- dt[dt$measurement %in% c('Distance','Energy'),]
> dt_cast <- dcast(dt2, subject+Try~measurement+speed+condition, value.var='result')

转换后的数据 (dt_cast) 将如下所示:

  subject  Try Distance_speed1_Control Distance_speed1_Experm Distance_speed2_Control
1       1 Try1                       1                      3                       5
2       1 Try2                       2                      4                       6
  Distance_speed2_Experm Energy_speed1_Control Energy_speed1_Experm Energy_speed2_Control
1                      7                    21                   23                    25
2                      8                    22                   24                    26
  Energy_speed2_Experm
1                   27
2                   28

例如,让我看看 Distance_speed1_Control 与 Energy_speed1_Control 列之间的关系。

基本上子集/聚合您的数据,然后使用 dcast 获取计算机需要的行和列。

这看起来是一个结构良好的数据集。您可以在wikipedia 的这一部分阅读有关数据库设计的更多信息您的数据结构良好,因此查询很容易。正如 Jake C 所说,您需要针对特定​​任务对其进行转换。像 dplr 和 reshape2 这样的软件包非常适合这一点。您还可以考虑将数据写入特定数据库。如果您的数据集太大以至于 R 用完 RAM,这将特别有用。我在这里用 SQLite 编写了一个示例:https ://scottishsnow.wordpress.com/2014/08/14/writing-to-a-database-r-and-sqlite/