Insert two data.table columns

dt <- data.table(L=1:5,A=letters[7:11],B=letters[12:16]) LAB 1: 1 gl 2: 2 hm 3: 3 in 4: 4 jo 5: 5 kp 

Now I want to insert the columns "A" and "B" to get a new one, name it "new":

 dt2 LAB new 1: 1 gl gl 2: 2 hm hm 3: 3 in in 4: 4 jo jo 5: 5 kp kp 
+7
r data.table
source share
4 answers

Arun's comment answered this question:

 dt[,new:=paste0(A,B)] 
+9
source share

I had a similar problem, but I had many columns, and I did not want to enter them manually.

A new version

(based on comment from @mnel)

 dt[, new:=do.call(paste0,.SD), .SDcols=-1] 

This is about two times faster than the old version and seems to wrap up quirks. Note the use of .SDcols to identify the columns used in paste0 . -1 uses all columns except the first, as the OP wanted to insert columns A and B, but not L.

If you want to use a different delimiter:

 dt[ , new := do.call(paste, c(.SD, sep = ":"))] 

Old version

You can use .SD and by to process multiple columns:

 dt[,new:=paste0(.SD,collapse=""),by=seq_along(L)] 

I added seq_along in case L was not unique. (You can verify this using dt<-data.table(L=c(1:4,4),A=letters[7:11],B=letters[12:16]) ).

Also, in my actual instance, for some reason I had to use t(.SD) in the paste0 part. There may be other similar quirks.

+9
source share

This should do it:

  dt <- data.table(dt, new = paste(dt$A, dt$B, sep = "")) 
-2
source share

If you want to insert strictly using column indices (if you don't know row names) ... I want to get a new column by inserting two columns 6 and 4

 dt$new <- apply( dt[,c(6,4)], 1, function(row){ paste(row[1],row[2],sep="/") }) 
-3
source share

All Articles