【问题标题】:reshape data into panel with multiple variables and no time variable in R将数据重塑为具有多个变量且在 R 中没有时间变量的面板
【发布时间】:2013-07-26 17:45:04
【问题描述】:

我是在 R 中重塑数据的新手,不知道如何使用 reshape()(或其他包)来创建面板数据。每个地理单位有两个时间观测值,但是每个时间观测值都被格式化为一个变量。例如:

subdistrict <- 1:4
control_t1 <- 5:8
control_t2 <- 9:12
motivation_t1 <- 12:15
motivation_t2 <- 16:19

data_mat <- as.data.frame(cbind(subdistrict, control_t1, control_t2, motivation_t1, motivation_t2))

data_mat
  subdistrict control_t1 control_t2 motivation_t1 motivation_t2
1           1          5          9            12            16
2           2          6         10            13            17
3           3          7         11            14            18
4           4          8         12            15            19

这里,control_t1 和 control_t2 分别指不同的时期。我的目标是重塑数据,以便可以建立时间变量并折叠命名变量以生成以下帧:

  subdistrict time control motivation
1           1            1         12            
1           2            5         16
2           1            2         13            
2           2            6         17
3           1            3         14            
3           2            7         18
4           1            4         15            
4           2            8         19

我不确定如何创建新的时间变量,以及如何折叠和重命名变量以重新塑造数据。感谢您的帮助。

【问题讨论】:

  • 目前,您的 data.frame 中的 colnames 和指定的变量名称不匹配。所以这个例子不能立即执行。为了大家的方便,可能想更正它。
  • 感谢您发现这一点;已编辑。

标签: r reshape


【解决方案1】:

您只需使用带有选项direction = "long"reshape() 函数。这是代码:

district <- 1:4
control_t1 <- 5:8
control_t2 <- 9:12
relax_t1 <- 12:15
relax_t2 <- 16:19
data_mat <- as.data.frame(cbind(district, control_t1, control_t2, relax_t1, relax_t2))
reshape(data = data_mat, direction = "long", idvar = "district", timevar = "time", varying = list(c(2:3), c(4:5)))
#     district time control_t1 relax_t1
# 1.1        1    1          5       12
# 2.1        2    1          6       13
# 3.1        3    1          7       14
# 4.1        4    1          8       15
# 1.2        1    2          9       16
# 2.2        2    2         10       17
# 3.2        3    2         11       18
# 4.2        4    2         12       19

查看R Programming wikibooks 了解更多信息。

【讨论】:

  • 还有reshape(data_mat, direction = "long", idvar = "district", varying = 2:ncol(data_mat), sep = "_"),需要进行一些清理以从自动创建的时间变量中去除“t”。
【解决方案2】:

一个简单的答案是将数据框拆分并重新绑定到您的新表单中,如下所示:

new_Data <- data.frame(
    subdistrict=data_mat[,1],
    control=unlist(data_mat[,2:3]),
    motivation=unlist(data_mat[,4:5]))

我们在这里所做的只是使用“unlist”函数将“控制”和“动机”两列折叠成单列数据,然后将它们全部绑定到一个新的数据框中。 'subdistrict' 数据重复,因此没有理由指定两次。

【讨论】:

  • 对于一小组变量来说可能很简单,但我怀疑人们是否希望使用具有多组变量的非常广泛的数据集来做到这一点......
  • @AnandaMahto 同意。编程和数据的权衡总是相同的:速度与灵活性。通常,最好的方法是在导入到 R 之类的统计包之前格式化数据,因为大多数数据库引擎更适合此类任务。我强烈建议任何人在 R 内部和外部找到多种格式化数据的方法,包括从低俗的解决方案到多态方法的所有方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多