简体   繁体   English

将空白读取为R数据表中的missing(NA)

[英]Read blank as missing(NA) in R data table

I am trying to create a function which can find missing location and impute the missing in a data table. 我正在尝试创建一个函数,该函数可以找到丢失的位置并在数据表中显示丢失的位置。 Now this function uses is.na() extensively to find out the missing location and also to replace it with imputation value. 现在,此函数广泛使用is.na()来查找丢失的位置,并将其替换为插补值。 It is working fine for all type of variable until input is character type column and have blank cells as missing, because is.na() is not able to identify it as missing hence it skips these cells for imputation. 对于所有类型的变量,它都可以正常工作,直到输入为character类型列并且缺少空白单元格为止,因为is.na()无法将其标识为缺少,因此跳过了这些单元格进行插补。

Example: 例:

    library(data.table)
    t<-data.table(x=c('an','ax','','az'),y=c('bn','','bz','bx'))
          x  y
      1: an bn
      2: ax      
      3:    bz 
      4: az bx
      is.na(t[,x])
      [1] FALSE FALSE FALSE FALSE

where it should be 应该在哪里

      [1] FALSE FALSE TRUE FALSE

Any help is highly appreciated. 非常感谢您的帮助。

Thanks. 谢谢。

You can use the fast nzchar like this : 您可以像这样使用快速的nzchar

is.na(x) | !nzchar(x) 

For example : 例如 :

x <- c(NA,'','a')
is.na(x) | !nzchar(x) 
## [1]  TRUE  TRUE FALSE

apply this to OP example: 将此应用于OP示例:

I wrap this in a function with ifelse : 我用ifelse将其包装在一个函数中:

tt <- data.table(x=c('an','ax','','az'),y=c('bn','','bz','bx'))
tt[, lapply(.SD,
            function(x)
              ifelse(is.na(x) | !nzchar(x),'some value',x)) ]

           x          y
1:         an         bn
2:         ax some value
3: some value         bz
4:         az         bx

Another solution using conditional assignment (using i ): 使用条件赋值的另一个解决方案(使用i ):

DT <- data.table(x = c('an','ax','','az',NA),
                 y = c(NA,'bn','','bz','bx'))
DT[x %in% c(NA, ""), x := 'some value']
DT[y %in% c(NA, ""), y := 'some value']

Result: 结果:

            x          y
1:         an some value
2:         ax         bn
3: some value some value
4:         az         bz
5: some value         bx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM