R语言 data.table将3列融为一体

2ul0zpep  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(118)

在合并了几个data.tables之后,我得到了一个看起来有点像这样的表:

dt<- data.table(age = rep(c("5-16", "17-39"), each = 3), dur = rep(c("short","medium","long"), 2), short.count = rep(c(23,45),each = 3), medium.count = rep(c(12,34), each = 3), long.count = rep(c(3,5), each = 3))

> dt

     age    dur short.count medium.count long.count
1:  5-16  short          23           12          3
2:  5-16 medium          23           12          3
3:  5-16   long          23           12          3
4: 17-39  short          45           34          5
5: 17-39 medium          45           34          5
6: 17-39   long          45           34          5

我想把它融化掉,这样每行就有一个(合适的)计数值。

age    dur       count 
1:  5-16  short          23           
2:  5-16 medium          12   
3:  5-16   long          3    
4: 17-39  short          45          
5: 17-39 medium          34           
6: 17-39   long          5

有没有一个优雅的方式来做到这一点?

eqqqjvef

eqqqjvef1#

您的数据实际上不需要melt,因为您已经为每个age和duration设置了一行。您可以使用fcase创建新的count列:

dt[, count:=fcase(
  dur=="short", short.count,
  dur=="medium", medium.count,
  dur=="long", long.count)][, c(1,2,6)]

输出:

age    dur count
1:  5-16  short    23
2:  5-16 medium    12
3:  5-16   long     3
4: 17-39  short    45
5: 17-39 medium    34
6: 17-39   long     5

相关问题