将Null更改为NA的函数 [英] Function to change Null to NA
问题描述
我试图编写一个将Null值转换为NA的函数。我的一个专栏的摘要如下所示:
ab
12 210 468
我想将12个空值更改为NA。我还有一些其他因素列,我想将Null值更改为NA,所以我借用了一些来自这里和那里的内容来提出这个问题:
#将nurse更改为NAs
nullToNA< - function(df){
#将df分隔为数字&非数字函数
a< -df [,sapply(df,is.numeric),drop = FALSE]
b <-df [,sapply(df,Negate(is.numeric)),drop (b),函数(x)等级(x)<-c(等级(x),NA))将空字符串改变为NA
b< -b [lapply ),#添加NA等级
b <-b [lapply(b,function(x)x [x ==,] < - NA),]#将Null更改为NA
#把列重新放在一起
d< -cbind(a,b)
d [,names(df)]
}
但是,我收到这个错误:
> foo< -nullToNA(bar)
x [x ==,] < - NA中的错误:矩阵
上下标的数目不正确。 ..)
我试过在这里找到的答案:将全部0个值全部替换为NA ,但它将我所有的列更改为数值。
您可以直接索引符合逻辑条件的字段。所以你可以写下:
$ $ $ $ $ $ $ $ $ c $ df [is_empty(df)] =
其中 is_empty
是您的比较,例如 df ==
:
df [df == ] = NA
但请注意 is.null(df)
不起作用,而且无论如何都会很奇怪。 1 。不过,我建议不要合并不同类型列的逻辑!
1 几乎不会遇到 NULL
,因为只有基础向量是 list
时才起作用。你可以用这个约束创建矩阵和数据框,但是 is.null(df)
永远不会是 TRUE
因为 NULL
值包装在列表中)。
I'm trying to write a function that turns Null values into NA. A summary of one of my column looks like this:
a b
12 210 468
I'd like to change the 12 empty values to NA. I also have a few other factor columns for which I'd like to change Null values to NA, so I borrowed some stuff from here and there to come up with this:
# change nulls to NAs
nullToNA <- function(df){
# split df into numeric & non-numeric functions
a<-df[,sapply(df, is.numeric), drop = FALSE]
b<-df[,sapply(df, Negate(is.numeric)), drop = FALSE]
# Change empty strings to NA
b<-b[lapply(b,function(x) levels(x) <- c(levels(x), NA) ),] # add NA level
b<-b[lapply(b,function(x) x[x=="",]<- NA),] # change Null to NA
# Put the columns back together
d<-cbind(a,b)
d[, names(df)]
}
However, I'm getting this error:
> foo<-nullToNA(bar) Error in x[x == "", ] <- NA : incorrect number of subscripts on matrix Called from: FUN(X[[i]], ...)
I have tried the answer found here: Replace all 0 values to NA but it changes all my columns to numeric values.
You can directly index fields that match a logical criterion. So you can just write:
df[is_empty(df)] = NA
Where is_empty
is your comparison, e.g. df == ""
:
df[df == ""] = NA
But note that is.null(df)
won’t work, and would be weird anyway1. I would advise against merging the logic for columns of different types, though! Instead, handle them separately.
1 You’ll almost never encounter NULL
inside a table since that only works if the underlying vector is a list
. You can create matrices and data.frames with this constraint, but then is.null(df)
will never be TRUE
because the NULL
values are wrapped inside the list).
这篇关于将Null更改为NA的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!