I'm using the data.table
package in R and want to perform an operation on a column. Specifically I want to enforce that all values are (0, 1).
Let's just work with a simple example here:
data = data.table(x = rnorm(10))
My data is stored as a data.table
so I was thinking that I could do something like this:
data[, newx := max(min(x, 1), 0)]
but the aggregate functions (min
and max
) compute the vector min/max.
Okay so I make a change an add a by=.I
statement:
data[, newx := max(min(x, 1), 0), by=.I]
but this doesn't work either!
What is the correct way, using data.table
, to accomplish this kind of task?