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

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

问题描述

我有一个数据框(14.5K 行 x 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)

不幸的是,这会产生警告:

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天全站免登陆