1
# 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)

The first example creates an outvariable with the correct values 1,2,3,4. The second variable creates an empty variable out as the which function returns integer(0) and apparently remove integer(0) from the check vector gives 0 elements.

I know how to write this in several lines but is there a one-liner for this?

zx8754
  • 52,746
  • 12
  • 114
  • 209
agoldev
  • 2,078
  • 3
  • 23
  • 38

3 Answers3

3

Try, is.finite():

# example 1
check <- c(1, 2, 3, 4, Inf)
out <- check[ is.finite(check) ]
out
# [1] 1 2 3 4

# example 2
check <- c(1, 2, 3, 4)
out <- check[ is.finite(check) ]
out
# [1] 1 2 3 4

Related post about: is.finite().

zx8754
  • 52,746
  • 12
  • 114
  • 209
1
check = c(1,2,3,4)
out   = check[!is.infinite(check)]
print(out)
simone
  • 577
  • 1
  • 7
  • 15
0

Not sure whether this is technically a oneliner...

out   = if (any(is.na(check))) {check[-which(is.na(check))]} else {check}
PejoPhylo
  • 469
  • 2
  • 11