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

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

问题描述

我有一个包含 2001 年到 2007 年的帐单数据的数据框(14.5K 行 x 15 列).

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)

不幸的是,会产生警告:

Unfortunately that generates a warning:

> 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)
)

我希望有一行看起来像:

I expect there be a row looks like:

            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,所以级别不会扩展.

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.

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

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