Good afternoon. I have a vector 'a' containing the following values:

`0 Nan 3.00 2.00 -7.00 9.00 Inf 54.00 ... NaN 6.00 Inf`

How can I sum inly numeric values wthin this vector?

I tried `sum(a,na.rm=TRUE)`

but it didn't help me.

Good afternoon. I have a vector 'a' containing the following values:

`0 Nan 3.00 2.00 -7.00 9.00 Inf 54.00 ... NaN 6.00 Inf`

How can I sum inly numeric values wthin this vector?

I tried `sum(a,na.rm=TRUE)`

but it didn't help me.

```
v <- c(0, NaN, 3.00, 2.00, -7.00, 9.00, Inf, 54.00, NaN, 6.00, Inf)
sum(v[which(!is.infinite(v))], na.rm = TRUE)
#or
sum(v[which(is.finite(v))], na.rm = TRUE)
```

lol, this kills me every time I see it! You can just subset with the logical vector returned by `is.finite()`

! My students do this all the time, `which()`

this and `which()`

that... I understand why they do it, it makes much more sense as you read the code aloud, it's just so unnecessary!

But, yes, this is the correct way to solve this. If you wanted something a little more compact though, I rather quite like this little hack of the language,

```
set.seed(123)
x <- c(sample(4), NA, Inf, 0)
sum(x^2/x, na.rm = TRUE)
#> [1] 10
```

Alternately you could do,

```
sum(x - x + x, na.rm = TRUE)
#> [1] 10
```

You should not do this though, you should use @nirgrahamuk's solution, it's correct.

^{Created on 2020-09-20 by the reprex package (v0.3.0)}

1 Like

Happy to amuse, and quite right too.

side effect of 'familiarity bias' where your mind reaches for the familiar before the most elegant...

`sum(v[is.finite(v)])`

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.