gented
gented

Reputation: 1707

Inline ifelse assignment in data.table

Let the following data set be given:

library('data.table')

set.seed(1234)
DT       <- data.table(x = LETTERS[1:10], y =sample(10))
my.rows  <- sample(1:dim(DT)[1], 3)

I want to add a new column to the data set such that, whenever the rows of the data set match the row numbers given by my.rows the entry is populated with, say, true, or false otherwise.

I have got DT[my.rows, z:= "true"], which gives

head(DT)
   x y    z
1: A 2   NA
2: B 6   NA
3: C 5 true 
4: D 8   NA
5: E 9 true 
6: F 4   NA

but I do not know how to automatically populate the else condition as well, at the same time. I guess I should make use of some sort of inline ifelse but I am lacking the correct syntax.

Upvotes: 4

Views: 2048

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389325

DT <- cbind(DT,z = ifelse(DT[, .I] %in% my.rows , T, NA))

> DT
#    x  y    z
# 1: A  2   NA
# 2: B  6   NA
# 3: C  5 TRUE
# 4: D  8   NA
# 5: E  9 TRUE
# 6: F  4   NA
# 7: G  1 TRUE
# 8: H  7   NA
# 9: I 10   NA
#10: J  3   NA

Upvotes: 0

akrun
akrun

Reputation: 887971

We can compare the 'my.rows' with the sequence of row using %in% to create a logical vector and assign (:=) it to create 'z' column.

 DT[, z:= 1:.N %in% my.rows ]

Or another option would be to create 'z' as a column of 'FALSE', using 'my.rows' as 'i', we assign the elements in 'z' that correspond to 'i' as 'TRUE'.

 DT[, z:= FALSE][my.rows, z:= TRUE]

Upvotes: 3

Related Questions