检查无限值时如何获得一致的输出

时间:2017-09-20 08:19:33

标签: r

# works fine
check = c(1,2,3,4, Inf)
out   = check[-which(check == Inf)]
print(out)
# [1] 1 2 3 4

# does not work fine 
check = c(1,2,3,4)
out   = check[-which(check == Inf)]
print(out)
# numeric(0)

第一个示例使用正确的值1,2,3,4创建out变量。第二个变量创建一个空变量out,因为哪个函数返回整数(0),显然从检查向量中删除整数(0)给出0个元素。

我知道怎么写这几行,但是有一个单行吗?

3 个答案:

答案 0 :(得分:3)

尝试,Time cost of producer: 390.58 ms Time cost of consumer: 561.85 ms Time cost of producer: 389.11 ms Time cost of consumer: 569.67 ms Time cost of producer: 402.26 ms Time cost of consumer: 568.95 ms Time cost of producer: 387.32 ms Avg time cost of producer: 559.29 ms Avg time cost of consumer: 560.05 ms

Time cost of producer: 381.25 ms
Time cost of producer: 479.66 ms
Time cost of consumer: 573.43 ms
Time cost of producer: 377.40 ms
Time cost of producer: 380.14 ms
Time cost of producer: 490.50 ms
Time cost of producer: 391.92 ms
Time cost of consumer: 682.74 ms
Time cost of producer: 389.05 ms
Avg time cost of producer: 205.45 ms
Time cost of producer: 480.88 ms
Avg time cost of producer: 206.14 ms
Time cost of consumer: 573.75 ms
Time cost of consumer: 256.17 ms
Time cost of consumer: 260.29 ms
Time cost of consumer: 260.84 ms
Time cost of consumer: 256.11 ms
......
Time cost of consumer: 271.39 ms
Time cost of consumer: 273.18 ms
Time cost of consumer: 286.35 ms
Avg time cost of consumer: 384.83 ms

相关帖子:is.finite()

答案 1 :(得分:1)

check = c(1,2,3,4)
out   = check[!is.infinite(check)]
print(out)

答案 2 :(得分:0)

不确定这在技术上是否是一个oneliner ...

out   = if (any(is.na(check))) {check[-which(is.na(check))]} else {check}