0

I have a datatable as below:

c1 <- c("a","e","b","f")
c2 <- c("b","a","a","c")
c3 <- c("x","x","x","x")
df <- data.table(c1, c2)

Trying to get a result that looks like this:

   c1 c2 new
1:  a  b ab
2:  e  a ae
3:  b  a ab
4:  f  c cf

I need the elements to be sorted before being concatenated as shown above

df[,new:=paste0(c1,c2)] works as expected but when I try to sort using df[,new:=paste0(sort(c1,c2))], there is a problem.

Also, in some cases, it seems that when one adds multiple functions (like sort() within paste()), the entire column is provided i.e. the operations are not strictly row-wise.

I tried concatenating first and then splitting the string to reorder. It did not work.

Thankyou

K_D
  • 147
  • 8
  • 1
    `df[, new_var := paste0(sort(.SD), collapse = ""), by = 1:nrow(df)]` – Ronak Shah Apr 21 '21 at 14:33
  • Thanks! What if there are more columns? This solution is pasting all the values in a row – K_D Apr 21 '21 at 14:40
  • 1
    You can specify the columns that you want to paste in `.SDcols`. `df[, new_var := paste0(sort(.SD), collapse = ""), by = 1:nrow(df), .SDcols = c('c1', 'c2')]` BTW `df <- as.data.table(c1, c2)` gives data table with only 1 column. – Ronak Shah Apr 21 '21 at 15:17
  • Yeah, I just figured out that `.SDcols` can be used along with `by`. I didn't know that adding it as a fourth 'argument' was allowed! Learn each day I guess. Changed `as.data.table` to `data.table`. Thanks! – K_D Apr 21 '21 at 16:11

0 Answers0