Convert list column to a string in place

Viewed 57

Suppose I have a DT as -

           id                    disabled      total_capacity         name                  ts 
     1:  5922                                   5400,5400              xin        2020-10-28 20:00:00   
     2:  5922                                   5400,5400              xin        2020-10-28 21:00:00   
     3:  5922                                   5400,5400              xin        2020-10-28 22:00:00   
     4:  5922                                   5400,5400              xin        2020-10-28 19:00:00   
     5:  5922                                   5400,5400              xin        2020-10-28 18:00:00  
100087: 434701                    500,200       2200,2200,2200,2200    xin        2020-10-28 18:00:00 
100088: 434701                        200       2200,2200,2200,2200    xin        2020-10-28 21:00:00 
100089: 434701                        200       2200,2200,2200,2200    xin        2020-10-28 20:00:00 
100090: 434701                        200       2200,2200,2200,2200    xin        2020-10-28 19:00:00 
100091: 434701                        200       2200,2200,2200,2200    xin        2020-10-28 22:00:00 

The columns total_capacity, disabled are lists.

> class(dt$total_capacity)
[1] "list"

I want to convert them to a string inplace for each row.

Expected output:

           id                    disabled      total_capacity         name                  ts 
     1:  5922                                   5400|5400              xin        2020-10-28 20:00:00   
     2:  5922                                   5400|5400              xin        2020-10-28 21:00:00   
     3:  5922                                   5400|5400              xin        2020-10-28 22:00:00   
     4:  5922                                   5400|5400              xin        2020-10-28 19:00:00   
     5:  5922                                   5400|5400              xin        2020-10-28 18:00:00  
100087: 434701                    500|200       2200|2200|2200|2200    xin        2020-10-28 18:00:00 
100088: 434701                        200       2200|2200|2200|2200    xin        2020-10-28 21:00:00 
100089: 434701                        200       2200|2200|2200|2200    xin        2020-10-28 20:00:00 
100090: 434701                        200       2200|2200|2200|2200    xin        2020-10-28 19:00:00 
100091: 434701                        200       2200|2200|2200|2200    xin        2020-10-28 22:00:00 

I have tried -

dt[,total_capacity:=paste(total_capacity, collapse='|'),]

But this adds the entire column into one row entry.

How do I do this correctly?

2 Answers

Use paste with sapply/lapply :

library(data.table)
dt[,total_capacity:= lapply(total_capacity,paste0, collapse = '|')]

We can use Map

library(data.table)
dt[, total_capacity := Map(paste0, MoreArgs = list(collapse= "|"), total_capacity)]
Related