8 r
我有一个矢量
x <- c(-1, 0, 1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
我希望所有小于1的值都替换为1.
怎么样?
有无循环解决方案吗?
其他解决方案更合适。这只是为了好玩:
(x > 1) * (x - 1) + 1
#[1] 1 1 1 2 3
Run Code Online (Sandbox Code Playgroud)
简单替换(@Matthew Lundberg)是最有效的解决方案:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20272 次 |
| 最近记录: |