Deb
Deb

Reputation: 539

How to Cbind a data.table and a vector

I want to cbind a data.table and a vector in such a way that the vector contents becomes new columns for the data.table with zero values.

DT <- data.table(x=c("A", "B", "C", "D", "E", "F"), y = rnorm(6))

DT2 <- c("paper11grid1", "paper12grid1", "paper13grid1")

I want to to update the contents of DT2 as new coumnnames of DT

 x          y     paper11grid1 paper12grid1 paper13grid1

 A  0.9643131           0   0   0

 B -0.8856350           0   0   0

 C -0.1489705           0   0   0

 D  2.0675105           0   0   0

 E -1.2965938           0   0   0

 F -0.8468514           0   0   0

A cbind directly will just add the DT2 as one coumn

cbind(DT, DT2)

Upvotes: 2

Views: 359

Answers (1)

Matt Summersgill
Matt Summersgill

Reputation: 4242

In data.table, you can assign values to multiple columns specified in a vector. With that approach, your answer is as simple as the following:

DT[,(DT2) := 0]

One distinction to note: even though DT2 is a valid vector, DT[, DT2 := 0] will simply result in a single new column named DT2. This has to do with the way that column names are evaluated within [...]. By using parenthesis -- (DT2) -- within the brackets, [.data.table will evaluate DT2 as a vector in this case, not a column name.

Upvotes: 7

Related Questions