替换R data.table中的Inf /以colum显示Inf的数量

时间:2015-05-20 15:20:25

标签: r data.table infinite na

我无法弄清楚如何使用is.na(x)函数对R中的无限数字进行数据表或每列显示有多少Inf的信息:colSums(is。无穷大(X))

我使用以下示例数据集:

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'

我在this post中找到了如何用NA替换Inf,但我想说应该有更好的方法来实现这一点,例如is.infinite。我希望看到每列的Inf,有关于此的任何想法吗?

非常感谢。 BR Tim

1 个答案:

答案 0 :(得分:5)

is.finiteis.infinite没有像data.frame这样的data.tableis.na方法(比较methods(is.infinite) vs { {1}})

您也可以循环遍历列,然后使用methods(is.na)

colSums

或者,您可以使用DT[, colSums(sapply(.SD, is.infinite))] # a b c # 2 0 1 代替Reduce

colSums

另一种选择是创建自己的自定义函数,然后将其循环遍历列

DT[, Reduce(`+`, lapply(.SD, is.infinite))]
## [1] 2 0 1

当然,您也可以为Myfunc <- function(x) sum(is.infinite(x)) DT[, lapply(.SD, Myfunc)] # a b c # 1: 2 0 1 编写data.frame方法,因为它似乎是通用的(请参阅is.infinite)。