2

我有一个大约 60 列的大小数据集,意外填充了NaN's 而不是NA's。列类型是字符、数字、因子、整数的混合。我需要将NaN's转换为 's,NA因为它们正在搞砸包括线性回归在内的几个函数的工作。我知道如何在此处更改此问题的单个列:

R 无法将 NaN 转换为 NA

但我很好奇是否有一种方法可以在不丢失矢量类型的情况下对完整数据帧执行此操作。有什么建议还是这是一项手工工作?

4

3 回答 3

1

gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
     fixed = FALSE, useBytes = FALSE)

工作?

也许您需要与apply. 您能否提供一个小示例,以便我可以尝试实现它?

谢谢。

于 2012-03-07T22:31:07.703 回答
1

这行得通吗?(它应该用于数字、整数、字符和因子向量。)

as.data.frame( lapply(dat, function(col) {
                 if (is.numeric(col)) { is.na(col) <- is.nan(col); return(col)} else {
                 if (is.character(col) || is.factor(col) )  {
                                              is.na(col) <- col == "NaN"; return(col)} else {
                 return(col)                                                                }
                                                                                     }
                                          }
               )

dat <- 
structure(list(tester1 = structure(c(1L, 1L, 2L, 3L, 1L, 2L, 
4L), .Label = c("2", "3", "4", "NaN"), class = "factor"), tester2 = c(2, 
2, 3, 4, 2, 3, NaN)), .Names = c("tester1", "tester2"), row.names = c(NA, 
-7L), class = "data.frame")

# Produced:

  tester1 tester2
1       2       2
2       2       2
3       3       3
4       4       4
5       2       2
6       3       3
7    <NA>      NA
于 2012-03-08T00:04:03.953 回答
-1

使用上述示例数据集。尝试这个:

CMBv = colnames(dat)

dat[CMBv] = lapply(dat[CMBv], function(x){ifelse(is.nan(x), NA,x)} )
于 2015-03-06T00:59:01.017 回答