user63764
user63764

Reputation: 41

R code: what does this combination of %in% and <- do?

data[data[["Id"]] %in% current[["Id"]], "Type"] <- "TRANS"

I'm confused, because there seems to be a conditional expression: data[data[["Id"]] %in% current[["Id"]], "Type"] combined with an assignment of a string: <- "TRANS"

Upvotes: 0

Views: 60

Answers (1)

IceCreamToucan
IceCreamToucan

Reputation: 28675

This is called “subassignment”. When data[i, j] is placed on the left-hand-side of <-, the subset of data selected is replaced with the right-hand-side of <-. Or, rephrased as in the docs:

help('[')

Indexing can occur on the right-hand-side of an expression for extraction, or on the left-hand-side for replacement. When an index expression appears on the left side of an assignment (known as subassignment) then that part of x is set to the value of the right hand side of the assignment

So what's happening here is due to [] and <- being combined and it would take place regardless of the function (%in%, seq, +, etc.) used to produce the i or j part of data[i, j]. The fact that %in% is used doesn't really have any impact here because it does same thing it would do without the assignment <-, i.e. produce a logical vector.

Upvotes: 1

Related Questions