【问题标题】:why NAs introduced by coercion happen when I Convert data type FACTOR to data frame?为什么当我将数据类型 FACTOR 转换为数据框时会发生强制引入的 NA?
【发布时间】:2018-04-30 09:47:08
【问题描述】:

我有一个 30 行和 100 列的数据框。此数据的某些列具有“nan”和“inf”值。瞬间,我创建了一个这样的数据框示例

test<-data.frame(a=c("inf",1,"inf"),b=c("nan",3,"nan"))
row.names(test)<-c("w1","w2",w)

当我想将 inf 和 nan 更改为零时,我尝试使用这些代码

na_codes<-"inf|nan"
test<-apply(test, 2, function(x){ ifelse(x %in% na_codes, 0, x) } )


test<-as.data.frame(lapply(test, function(x) {
  levels(x)[levels(x) %in% na_code] <- 0 
  x
  })
)
但只有使用此代码,我才能实现理想的输出。
test<-type.convert(sub("inf|nan", 0, as.matrix(test)))

但是我的数据的类变成了factor! 当我想规范化我的数据时,我使用了这段代码

normalize<-function(x){
  return((x-min(x))/(max(x)-min(x)))
}
norm_test<-sapply(data.frame(test),normalize)

它崩溃返回以下消息:

 Error in Summary.factor(766L, na.rm = FALSE) : 
  ‘min’ not meaningful for factor

我想将因子转换为数值类,所以使用了这段代码

norm_test<-sapply(data.frame(as.numeric(as.character(test))),normalize)

不幸的是,它也会崩溃返回以下警告

Warning message:
In data.frame(as.numeric(as.character(num_base))) :
  NAs introduced by coercion

实际上,这些代码适用于我上面提到的测试样本,我在 我的数据 中遇到了这些错误!!!!

我需要了解为什么会发生崩溃以及如何防止此类错误。

非常感谢!

【问题讨论】:

    标签: r


    【解决方案1】:

    这似乎是替换NAs 和Infs 的一种非常复杂的方式。不幸的是,您没有分享任何示例数据,也没有提供函数normalize 的详细信息,所以我不确定您的数据是什么样的。

    在下面我假设您有一个 matrixdata.framenumeric 值,以及一些 NAInf 的条目。

    这个怎么样:

    # Sample data
    set.seed(2017);
    df <- matrix(rnorm(20), ncol = 4);
    df[2, 2] <- Inf;
    df[3, 3] <- NA;
    
    # Replace NAs and Infs with 0
    df[is.na(df) | is.infinite(df)] <- 0;
    df;
    #            [,1]         [,2]       [,3]       [,4]
    #[1,]  1.43420148  0.451905527  0.3427681  1.1944265
    #[2,] -0.07729196  0.000000000  1.5724254 -0.4820681
    #[3,]  0.73913723 -0.001524259  0.0000000  1.3178624
    #[4,] -1.75860473 -0.265336001  0.3066498 -1.1298316
    #[5,] -0.06982523  1.563222619 -1.4304858 -0.9263514
    

    【讨论】:

    • 感谢您的回复。正如你所说,我已经编辑了我的问题。
    • 其实我的问题不是如何用0替换inf和nan!!!我的问题是为什么会发生这个错误
    猜你喜欢
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多