【发布时间】:2017-03-10 10:06:03
【问题描述】:
我是 R 的相对新手,并试图将我的数据从宽格式重塑为长格式并遇到问题。我在想我的问题可能是由于从我在 R 中创建的 data.frame 制作了 data.frame,将大 data.frame 的平均值转换为另一个 data.frame。
我所做的是这创建了一个空的 data.frame (ndf):
ndf <- data.frame(matrix(ncol = 0, nrow = 3))
然后使用 lapply 将大 data.frame (ldf) 中的平均值放入新 data.frame 中的单独列中,使用大 data.frame 中的年份:
ndf$Year <- names(ldf)
ndf$col1 <- lapply(ldf, function(i) {mean(i$col1)})
ndf$col2 <- lapply(ldf, function(i) {mean(i$col2)})
etc.
reshape2 中的 melted 函数显然不起作用,因为存在非原子“测量”列。
为了使用 reshape 基函数,我使用了代码:
reshape.ndf <- reshape(ndf,
varying = list(names(ndf)[2:7]),
v.names = "cover",
timevar = "species",
times = names(ndf[2:7]),
new.row.names = 1:1000,
direction = "long")
然后,我的输出基本上只是将第一行用于变量。所以我的宽 data.frame 看起来像这样(对不起,奇怪的名字):
Year Cladonia.portentosa Erica.tetralix Eriophorum.vaginatum
1 2014 11.75 35 55
2 2015 15.75 25.75 70
3 2016 22.75 5 37.5
而长 data.frame 看起来像这样:
Year species cover id
1 2014 Cladonia.portentosa 11.75 1
2 2015 Cladonia.portentosa 11.75 2
3 2016 Cladonia.portentosa 11.75 3
4 2014 Erica.tetralix 35.00 1
5 2015 Erica.tetralix 35.00 2
6 2016 Erica.tetralix 35.00 3
“封面”列应将每年的值放入对应年份的单元格中。
请有人告诉我哪里出错了!?
【问题讨论】:
-
当您的宽数据中只有 4 列时,如何使用
names(ndf[2:7])? -
你试过
tidyr::gather()吗?如果没有,请检查一下。它基本上是reshape2的继任者。 -
42 - 我只展示了数据集的一部分,我试图减少混淆,但忘记更改代码以表示我所展示的内容。
-
@roman - 我调查了 'gather()_' 但可能不够彻底。我会再试一次并报告