使用

时间:2018-08-02 15:02:51

标签: r data.table melt

我有一个data.table,其中我想要的数据以对角线的形式构造。

library(data.table)
month <- c(201406, 201406, 201406, 201406, 201406, 201406, 201406, 201406, 
201406, 201406, 201406, 201406)
code <- c("498A01", "498A01", "498A01", "498A01", "498A01", "498A01", "498A01", "498A01", 
"498A01", "498A01", "498A01", "498A01")
col.a <- c("service", "base charge", "", "", "", "", "", "", "", "", "", "")
col.b <- c("", "", "description", "per unit", "", "", "", "", "", "", "", "")
col.c <- c("", "", "", "", "rate", 6859, "", "", "", "", "", "")
col.d <- c("", "", "", "", "", "", "quantity", 1, "", "", "", "")
col.e <- c("", "", "", "", "", "", "", "", "total charge", 6859, "", "")
col.f <- c("", "", "", "", "", "", "", "", "", "", "", "")   
dt <- data.table(month, code, col.a, col.b, col.c, col.d, col.e, col.f)

但是,我需要以更连贯的方式组织数据以简化dt 我是data.table的新手,我想知道是否有直接的方法。

对于col.a,我知道以下内容适用于一列:

dt <- dt[col.a != "", 1:8, by = .(code, month)

但是当我尝试多列时,它会返回0 obs的数据表。我想我可以对所有列进行此操作,然后进行某种合并,但这似乎效率低下且麻烦。有更好的方法吗?

我想要的输出是:

   month   code      col.a      col.b     col.c   col.d       col.e    col.f
1: 201406 498A01     service description   rate quantity total charge       
2: 201406 498A01 base charge    per unit   6859        1         6859 

因此,对于codemonth的每个唯一组合,我想删除空单元格并折叠数据以使其看起来像上面一样。我需要保留col.f1,因为它不一定总是空白。

任何建议将不胜感激。

1 个答案:

答案 0 :(得分:3)

您是否正在寻找类似的东西

dt[, lapply(.SD, function(x) x[x!=""][1:2]), by=.(month, code)]

输出:

    month   code       col.a       col.b col.c    col.d        col.e col.f
1: 201406 498A01     service description  rate quantity total charge  <NA>
2: 201406 498A01 base charge    per unit  6859        1         6859  <NA>

或在基数R中:

do.call(rbind, by(dt, paste(dt$month, dt$code), 
    function(y) do.call(cbind, lapply(y, function(x) x[x!=""][1:2]))))

输出:

     month    code     col.a         col.b         col.c  col.d      col.e          col.f
[1,] "201406" "498A01" "service"     "description" "rate" "quantity" "total charge" NA   
[2,] "201406" "498A01" "base charge" "per unit"    "6859" "1"        "6859"         NA