I can't figure out how to use an is.na(x) like function for infinite numbers in R with a data table or show per column how many Inf's there are: colSums(is.infinite(x))
I use the following example data set:
DT <- data.table(a=c(1/0,1,2/0),b=c("a","b","c"),c=c(1/0,5,NA))
DT
a b c
1: Inf a Inf
2: 1 b 5
3: Inf c NA
colSums(is.na(DT))
a b c
0 0 1
colSums(is.infinite(DT))
Error in is.infinite(DT) : default method not implemented for type 'list'
DT[is.na(DT)] <- 100
DT
a b c
1: Inf a Inf
2: 1 b 5
3: Inf c 100
DT[is.infinite(DT)] <- 100
Error in is.infinite(DT) : default method not implemented for type 'list'
I found in this post how to replace Inf with NA, but I would say there should be nicer way of achieving this, with is.infinite for example. And I would like to see the Inf's per column, any ideas about this?
Many thanks. BR Tim
is.finite
and is.infinite
don't have a data.frame
or a data.table
methods like is.na
has (compare methods(is.infinite)
vs methods(is.na)
)
You could alternatively loop thru the columns and then use colSums
DT[, colSums(sapply(.SD, is.infinite))]
# a b c
# 2 0 1
Alternatively, you could use Reduce
instead of colSums
DT[, Reduce(`+`, lapply(.SD, is.infinite))]
## [1] 2 0 1
Another option is to create your own custom function and then just loop it over the columns
Myfunc <- function(x) sum(is.infinite(x))
DT[, lapply(.SD, Myfunc)]
# a b c
# 1: 2 0 1
Of course you could also write data.frame
method for is.infinite
as it appears to be generic (see ?is.infinite
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With