简体   繁体   中英

Restrict column to specific range using data.table in R

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?

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

您也可以尝试简单的ifelse

data[, newX:= ifelse(x >1,1,x)][, newX:= ifelse(x < 0, 0,x)]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM