将空白更改为 NA 的功能
Function to change blanks to NA
我正在尝试编写一个将空字符串转换为 NA 的函数。我的一个专栏的摘要如下所示:
a b
12 210 468
我想将 12 个空值更改为 NA。我还有一些其他因素列,我想将它们的空值更改为 NA,所以我从这里和那里借了一些东西来想出这个:
# 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)]
}
但是,我收到了这个错误:
> foo<-nullToNA(bar)
Error in x[x == "", ] <- NA : incorrect number of subscripts on matrix
Called from: FUN(X[[i]], ...)
我已尝试在此处找到答案:Replace all 0 values to NA 但它会将我的所有列都更改为数值。
怎么样:
df[apply(df, 2, function(x) x=="")] = NA
对我来说效果很好,至少在简单的例子上是这样。
您可以直接索引符合逻辑条件的字段。所以你可以写:
df[is_empty(df)] = NA
其中 is_empty
是您的比较,例如df == ""
:
df[df == ""] = NA
但请注意 is.null(df)
不会起作用,而且无论如何都会很奇怪1。不过,我建议不要合并不同类型列的逻辑!相反,请单独处理它们。
1 你几乎永远不会在 table 中遇到 NULL
因为只有当基础向量是 list
时才有效。您可以使用此约束创建矩阵和 data.frames,但是 is.null(df)
永远不会是 TRUE
,因为 NULL
值包含在列表中)。
这对我有用
df[df == 'NULL'] <- NA
这是我用来解决这个问题的函数。
null_na=function(vector){
new_vector=rep(NA,length(vector))
for(i in 1:length(vector))
if(vector[i]== ""){new_vector[i]=NA}else if(is.na(vector[i]))
{new_vector[i]=NA}else{new_vector[i]=vector[i]}
return(new_vector)
}
只需插入您遇到问题的列或向量。
我正在尝试编写一个将空字符串转换为 NA 的函数。我的一个专栏的摘要如下所示:
a b
12 210 468
我想将 12 个空值更改为 NA。我还有一些其他因素列,我想将它们的空值更改为 NA,所以我从这里和那里借了一些东西来想出这个:
# 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)]
}
但是,我收到了这个错误:
> foo<-nullToNA(bar) Error in x[x == "", ] <- NA : incorrect number of subscripts on matrix Called from: FUN(X[[i]], ...)
我已尝试在此处找到答案:Replace all 0 values to NA 但它会将我的所有列都更改为数值。
怎么样:
df[apply(df, 2, function(x) x=="")] = NA
对我来说效果很好,至少在简单的例子上是这样。
您可以直接索引符合逻辑条件的字段。所以你可以写:
df[is_empty(df)] = NA
其中 is_empty
是您的比较,例如df == ""
:
df[df == ""] = NA
但请注意 is.null(df)
不会起作用,而且无论如何都会很奇怪1。不过,我建议不要合并不同类型列的逻辑!相反,请单独处理它们。
1 你几乎永远不会在 table 中遇到 NULL
因为只有当基础向量是 list
时才有效。您可以使用此约束创建矩阵和 data.frames,但是 is.null(df)
永远不会是 TRUE
,因为 NULL
值包含在列表中)。
这对我有用
df[df == 'NULL'] <- NA
这是我用来解决这个问题的函数。
null_na=function(vector){
new_vector=rep(NA,length(vector))
for(i in 1:length(vector))
if(vector[i]== ""){new_vector[i]=NA}else if(is.na(vector[i]))
{new_vector[i]=NA}else{new_vector[i]=vector[i]}
return(new_vector)
}
只需插入您遇到问题的列或向量。