将带有看不见的字符串值的新记录追加到数据框时出现看不见的因子级别,导致警告并导致不适用 [英] Unseen factor levels when appending new records with unseen string values to a dataframe, cause Warning and result in NA

查看:111
本文介绍了将带有看不见的字符串值的新记录追加到数据框时出现看不见的因子级别,导致警告并导致不适用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据帧(14.5K行乘15列),其中包含2001年至2007年的帐单数据。

I have a dataframe (14.5K rows by 15 columns) containing billing data from 2001 to 2007.

我将新的2008年数据附加到其中: alltime<-rbind(alltime,all2008)

I append new 2008 data to it with: alltime <- rbind(alltime,all2008)

不幸的是,生成警告:

> Warning message:
In `[<-.factor`(`*tmp*`, ri, value = c(NA, NA, NA, NA, NA, NA, NA,  :
  invalid factor level, NAs generated

我的猜测是,有些新患者的姓名不在以前的数据框中

My guess is that there are some new patients whose names were not in the previous dataframe and therefore it would not know what level to give those. Similarly new unseen names in the 'referring doctor' column.

有什么解决方案?

推荐答案

这可能是由于两个 data.frames 中的类型不匹配引起的。

It could be caused by mismatch of types in two data.frames.

首先检查类型(类),以达到诊断目的:

First of all check types (classes). To diagnostic purposes do this:

new2old <- rbind( alltime, all2008 ) # this gives you a warning
old2new <- rbind( all2008, alltime ) # this should be without warning

cbind(
    alltime = sapply( alltime, class),
    all2008 = sapply( all2008, class),
    new2old = sapply( new2old, class),
    old2new = sapply( old2new, class)
)

我希望会有这样的行:

            alltime  all2008   new2old  old2new
...         ...      ...       ...      ...
some_column "factor" "numeric" "factor" "character"
...         ...      ...       ...      ...

然后说明:
rbind 不检查类型是否匹配。如果分析 rbind.data.frame 代码,则可以看到第一个参数初始化了输出类型。如果在第一个data.frame类型中是一个因子,则输出data.frame列是级别 unique(c(levels(x1),levels(x2)))的因子。但是,当第二个data.frame列中的值不重要时, levels(x2) NULL ,因此级别不t扩展。

If so then explanation: rbind don't check types match. If you analyse rbind.data.frame code then you could see that the first argument initialized output types. If in first data.frame type is a factor, then output data.frame column is factor with levels unique(c(levels(x1),levels(x2))). But when in second data.frame column isn't factor then levels(x2) is NULL, so levels don't extend.

这表示您的输出数据有误!有 NA 而不是真实值

It means that your output data are wrong! There are NA's instead of true values

我认为:


  1. 您使用另一个R / RODBC版本创建了旧数据,因此使用不同的方法(不同的设置-可能是小数点分隔符)创建了类型

  2. 有问题的列中有NULL或某些特定数据,例如。

解决方案:

找到错误的列并找到其错误和固定的原因。消除原因而不是症状。

find wrong column and find reason why its's wrong and fixed. Eliminate cause not symptoms.

这篇关于将带有看不见的字符串值的新记录追加到数据框时出现看不见的因子级别,导致警告并导致不适用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆