Reputation: 2206
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?
Upvotes: 1
Views: 699
Reputation: 2832
You can also try simple ifelse
i.e.
data[, newX:= ifelse(x >1,1,x)][, newX:= ifelse(x < 0, 0,x)]
Upvotes: 2
Reputation: 34703
Simpler and faster would be to just define it piecewise:
set.seed(13084)
data = data.table(x = rnorm(10))
> data[ , newx := (xg1 <- x > 1) + x * (!xg1 & x > 0)][]
x newx
1: 0.7842597 0.7842597
2: -0.3935582 0.0000000
3: -2.3379063 0.0000000
4: -1.7428335 0.0000000
5: 0.1678035 0.1678035
6: -0.9558911 0.0000000
7: -1.5592778 0.0000000
8: 0.9358569 0.9358569
9: 0.7778178 0.7778178
10: 1.0937594 1.0000000
Upvotes: 1
Reputation: 18602
You can create a dummy index and drop it when it is no longer needed, like this:
data[,Idx := .I][, newx := max(min(x, 1), 0), by = "Idx"][, Idx := NULL][]
# x newx
# 1: 1.12585452 1.0000000
# 2: 0.82343338 0.8234334
# 3: -1.02227889 0.0000000
# 4: 1.42761362 1.0000000
# 5: 0.77371518 0.7737152
# 6: -0.22261010 0.0000000
# 7: -0.64862015 0.0000000
# 8: -0.45663845 0.0000000
# 9: -0.96332902 0.0000000
# 10: -0.04396755 0.0000000
Upvotes: 3