我编写了一个将R中的Inf / NaN值转换为NA的函数。功能如下:
DSanity.replaceInfNan <- function(l)
{
l <- ifelse((is.infinite(l))|(is.nan(l)), NA, l);
return(l)
}
但是,当class(l)是一个因子时,该函数返回一个类integer的对象。在没有明确检查类因子的情况下获得相同类的任何解决方案?下面给出一个例子。
dput(m)
structure(c(2L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L,
22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 2L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L, 11L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L,
12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L,
25L, 26L, 27L, 2L, 3L, 4L, 2L, 3L, 4L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L), .Label = c("1984", "1985", "1986", "1987", "1988", "1989",
"1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997",
"1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005",
"2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013"
), class = "factor")
class(DSanity.replaceInfNan(m))
"integer"
答案 0 :(得分:3)
DSanity.replaceInfNan <- function(l) {
l[is.infinite(l) | is.nan(l)] <- NA
return(l)
}