user1322720
user1322720

Reputation:

Replace all values lower than threshold in R

I have a vector

x <- c(-1, 0, 1, 2, 3)

I want all values less than 1 to be replaced by 1.

How?

Is there a no-loop solution?

Upvotes: 10

Views: 36707

Answers (4)

loki
loki

Reputation: 10350

Another option would be replace:

x <- c(-1, 0, 1, 2, 3)

replace(x, x < 1,1)
# [1] 1 1 1 2 3

Upvotes: 3

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

The other solutions are more appropriate. This is just for fun:

(x > 1) * (x - 1) + 1
#[1] 1 1 1 2 3

Simple replacement (@Matthew Lundberg) is the most efficient solution:

library(microbenchmark)
microbenchmark(pmax(1, x),
               "[<-"(x, x < 1, 1),
               (x > 1) * (x - 1) + 1)

# Unit: microseconds
#                   expr    min      lq  median      uq    max neval
#             pmax(1, x) 15.494 16.2545 16.5165 16.9365 52.165   100
#     `[<-`(x, x < 1, 1)  1.466  1.6920  2.3325  2.7485 23.683   100
#  (x > 1) * (x - 1) + 1  2.084  2.2870  2.7880  3.2080  8.958   100

Upvotes: 7

Matthew Lundberg
Matthew Lundberg

Reputation: 42659

Use logical indexing with replacement:

x[ x<1 ] <- 1

Upvotes: 30

Jilber Urbina
Jilber Urbina

Reputation: 61164

pmax is a good candidate for this

  > pmax(x, 1)
    [1] 1 1 1 2 3

Upvotes: 10

Related Questions