LeGeniusII
LeGeniusII

Reputation: 960

R data.table create multiple columns in one go

This question is about a specific data.table operation.

I have:

dataDT <- data.table(ID = c(1:3))
dataDT
> dataDT
   ID
1:  1
2:  2
3:  3

I want to create three new columns to store data from 3 different sources.

targetDT <- data.table(ID = c(1:3), ID1 = c(1:3), ID2 = c(1:3), ID3 = c(1:3))
targetDT
> targetDT
   ID ID1 ID2 ID3
1:  1   1   1   1
2:  2   2   2   2
3:  3   3   3   3

So I've tried:

tempDT_1 <- data.table(ID1 = c(1:3))    # create dummy source 1
tempDT_2 <- data.table(ID2 = c(1:3))    # create dummy source 2
tempDT_3 <- data.table(ID3 = c(1:3))    # create dummy source 3

dataDT[, c("A", "B", "c") := list(tempDT_1, tempDT_2, tempDT_3)]
dataDT
> dataDT
   ID     A     B     c
1:  1 1,2,3 1,2,3 1,2,3
2:  2 1,2,3 1,2,3 1,2,3
3:  3 1,2,3 1,2,3 1,2,3

Why the above list(tempDT_1, tempDT_2, tempDT_3) "not working properly"?

I have seen people do things like:

dataDT[, c("A", "B", "c") := list(sum(ID), mean(ID), func(ID))]

that uses list() to "cbind" new values.

How should I fix my codes?

Upvotes: 1

Views: 59

Answers (2)

akrun
akrun

Reputation: 887118

If we need to make replicates, an option is replicate

setDT(data.frame(replicate(4, dataDT)))[]
#   ID ID.1 ID.2 ID.3
#1:  1    1    1    1
#2:  2    2    2    2
#3:  3    3    3    3

Or use assign (:=)

dataDT[, paste0('ID', 1:3) := ID][]

Upvotes: 1

BENY
BENY

Reputation: 323226

Since

class(tempDT_1 )
[1] "data.table" "data.frame" 

In your case to match the output we should using cbind

cbind(dataDT, tempDT_1, tempDT_2, tempDT_3)
   ID ID1 ID2 ID3
1:  1   1   1   1
2:  2   2   2   2
3:  3   3   3   3

Upvotes: 1

Related Questions