且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用列模式融化数据表

更新时间:2023-11-18 18:58:34

我将玻璃杯举起@rawr,他显然了解base-R reshape 函数。对我来说,这是一个永恒的谜,尽管人们在理解文档方面做出了很多努力,并且在解决问题上也做出了很多努力。尽管我对通过通用的非标准化来简化(但令我感到困惑)R的复杂工作普遍不屑一顾,但我发现他发明了 reshape2 :: melt -function

I raise my glass to @rawr who apparently understands the base-R reshape-function. For me it is an eternal mystery, despite many efforts at understanding its documentation and many efforts at solving problems with it. Despite my general disdain for the hadleyverse efforts at "simplifying" (but for me obfuscating) R by universal "nonstandardization", I find his invention of the reshape2::melt-function to be a great aid in efficient manipulation.

require(reshape2)
> melt(dat, id.var="id")
  id variable value
1  1   A1g_hi     2
2  1   A2g_hi     3
3  1   A3g_hi     4
4  1   A4g_hi     5
> str(melt(dat, id.var="id"))
'data.frame':   4 obs. of  3 variables:
 $ id      : int  1 1 1 1
 $ variable: Factor w/ 4 levels "A1g_hi","A2g_hi",..: 1 2 3 4
 $ value   : int  2 3 4 5

所以:

> dat2[[2]] <- as.numeric(dat2[[2]])
> dat2
  id variable value
1  1        1     2
2  1        2     3
3  1        3     4
4  1        4     5