【问题标题】:melt a data.table with a column pattern使用列模式融化 data.table
【发布时间】:2016-06-26 02:15:31
【问题描述】:

我有一个data.table,看起来像这样:

id A1g_hi A2g_hi A3g_hi A4g_hi
1  2      3      4      5
...

我想melt这个表,让它看起来像这样:

id time hi
1  1    2
1  2    3
1  3    4
1  4    5
...

我尝试过这样的事情:

melt(dtb, measure.vars = patterns("^A"), value.name = "hi", variable.name="time")

这并没有给我想要的东西。我需要在这里使用字符串拆分还是有本地的 data.table 函数可以做到这一点?

【问题讨论】:

  • 时间是一个因素,所以您可以将其转换为整数?仅供参考基础重塑给你你想要的reshape(dd, dir = 'long', idvar = 'id', varying = list(2:5), v.names = 'hi')

标签: r data.table reshape reshape2


【解决方案1】:

我向@rawr 举杯,他显然了解base-R reshape-函数。对我来说,这是一个永恒的谜,尽管在理解它的文档方面付出了很多努力,并为解决它的问题付出了很多努力。尽管我普遍鄙视 hadleyverse 在通过通用“非标准化”“简化”(但对我来说是混淆)R 的努力,但我发现他发明的 reshape2::melt-function 对有效操作很有帮助。

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

【讨论】:

    【解决方案2】:

    我可以建议一个简单的dplyr+tidyr 解决方案。

    library(data.table)
    library(dplyr)
    library(tidyr)
    
    dt <- as.data.table(read.table(text = "id A1g_hi A2g_hi A3g_hi A4g_hi
    1  2      3      4      5", header = T))
    
    dt %>% gather(time, hi, -id) %>% mutate(time = extract_numeric(time))
    
      id time hi
    1  1    1  2
    2  1    2  3
    3  1    3  4
    4  1    4  5
    

    【讨论】:

    • 不需要as.data.table(read.table(...)) 的东西。只需fread("id A1g_hi A2g_hi A3g_hi A4g_hi\n1 2 3 4 5") %&gt;% gather(time, h1, -id) %&gt;% mutate(time = extract_numeric(time))
    • 感谢@Ananda 的指点,我尝试使用fread 指定text = 参数并得到错误,然后使用read.table 的语法
    猜你喜欢
    • 2023-03-29
    • 2013-01-11
    • 2016-12-31
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 2022-11-10
    相关资源
    最近更新 更多