我寫了一個函數,將R中的Inf/NaN值轉換爲NA。函數如下:因子和Inf/NaN
DSanity.replaceInfNan <- function(l)
{
l <- ifelse((is.infinite(l))|(is.nan(l)), NA, l);
return(l)
}
但是,當類(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"
如果你的功能是專爲因素,您可在水平/標籤操作來代替。如果不是,明確的檢查似乎是需要的。這有什麼不好? – tonytonov