Stéphane Laurent
Stéphane Laurent

Reputation: 84719

Replace a value in a datatable by giving the column index

Let DT be this datatable:

DT <- data.table(A=1:2, B=3:4)

We can replace the cell at row 2 of column B like this:

DT[2, `:=`(B=99)]

But I would like to replace by giving the index of the column, not its name. How?

Upvotes: 2

Views: 820

Answers (2)

M--
M--

Reputation: 29237

You can use what @MrFlick commented or simply use this: DT[2,2] <- 99

I don't know what's your preference for using that notation.

Upvotes: 1

MrFlick
MrFlick

Reputation: 206586

You can pass a numeric index as a first parameter to :=. For example

DT[2, `:=`(2, 99)]

Upvotes: 5

Related Questions