data.table 中的按行制表

rowwise tabulation in data.table

有一个data.table如下:

   station       w_1       w_2
1:    1757     ar_2d lm_h_step
2:    2171 lm_h_step lm_h_step
3:    2812 lm_h_step lm_h_step
4:    4501 lm_h_step lm_h_step
5:    4642     ar_2d lm_h_step
6:    5029     ar_2d lm_h_step
7:    5480 lm_h_step lm_h_step
8:    5779     ar_2d     ar_2d
9:    5792     ar_1d     ar_2d

我想列出每个站的方法频率。
所以预期的结果是

          1757  2171  2812 ...
lm_h_step    1     2     2
ar_2d        1     0     0 
ar_1d        0     0     0 ...

到目前为止我尝试过的:

apply(dat,1,table)

产生了正确的结果,但格式不正确。

有什么想法吗?

数据输入:

structure(list(station = c(1757L, 2171L, 2812L, 4501L, 4642L, 
                           5029L, 5480L, 5779L, 5792L), w_1 = c("ar_2d", "lm_h_step", "lm_h_step", 
                                                                "lm_h_step", "ar_2d", "ar_2d", "lm_h_step", "ar_2d", "ar_2d"), 
               w_2 = c("lm_h_step", "lm_h_step", "lm_h_step", "lm_h_step", 
                       "lm_h_step", "lm_h_step", "lm_h_step", "ar_2d", "ar_2d")), .Names = c("station", 
                                                                                             "w_1", "w_2"), class = c("data.table", "data.frame"), row.names = c(NA, 
                                                                                                                                                                 -9L))

尝试dcast/melt组合

对于 data.table v >= 1.9.5 使用这个

dcast(melt(dat, "station"), value ~ station, length)
#        value 1757 2171 2812 4501 4642 5029 5480 5779 5792
# 1:     ar_1d    0    0    0    0    0    0    0    0    1
# 2:     ar_2d    1    0    0    0    1    1    0    2    1
# 3: lm_h_step    1    2    2    2    1    1    2    0    0

对于 data.table v < 1.9.5 您还需要加载 reshape2 并显式使用 dcast.data.table(因为 reshape2::dcast 不是通用的并且 没有 dcast.data.table 方法)。

另一方面,

reshape2::melt 是通用的(参见 methods(melt))并且有一个 melt.data.table 方法,所以您不需要告诉它任何东西。它会根据 dat

class 知道您要使用哪种方法
require(reshape2)
dcast.data.table(melt(dat, "station"), value ~ station, length)
#        value 1757 2171 2812 4501 4642 5029 5480 5779 5792
# 1:     ar_1d    0    0    0    0    0    0    0    0    1
# 2:     ar_2d    1    0    0    0    1    1    0    2    1
# 3: lm_h_step    1    2    2    2    1    1    2    0    0

如果您对严格使用 data.table 方法不挑剔,您也可以使用 reshape2::recast(请参阅@shadows 评论),它是上述解决方案的包装器,但使用 reshape2::dcast而不是 dcast.data.table,因此 return 将是一个 data.frame 对象而不是 data.table

recast(dat, value ~ station, id.var = "station", length)
#       value 1757 2171 2812 4501 4642 5029 5480 5779 5792
# 1     ar_1d    0    0    0    0    0    0    0    0    1
# 2     ar_2d    1    0    0    0    1    1    0    2    1
# 3 lm_h_step    1    2    2    2    1    1    2    0    0