[英]How do I convert a text string of NULL to a number?
I have input data from SQL which has fields that are the string "NULL", such that 我有来自SQL的输入数据,其中的字段为字符串“ NULL”,例如
unique(file$x)
returns 退货
Levels: 1 10 14 8 NULL
I would like any of the results that are "NULL" to become "0" and then to convert using as.numeric(). 我希望“ NULL”的任何结果都变为“ 0”,然后使用as.numeric()进行转换。
I have tried: 我努力了:
i <- 1
for(i <= nrow(file) {
if(file$x[i] == "NULL") {
file$x[i] <- 0
}
i <- i + 1
}
However, I get the result now that the NULL has simply turned into and I am still unable to convert it to the number 0. 但是,我现在得到的结果是NULL变成了NULL,但仍然无法将其转换为数字0。
If you're reading this in with read.csv
, set the option na.strings='NULL'
. 如果要使用
read.csv
阅读,请设置选项na.strings='NULL'
。 This will import file$x
as numeric
, instead of factor
, with numeric NA
s objects in place of the NULL
strings. 这会将
file$x
导入为numeric
而不是factor
,使用数字NA
s对象代替NULL
字符串。 Then to replace NA
s with 0
s: 然后将
NA
替换为0
s:
file$x[is.na(file$x)] <- 0
In your SQL Query add: ISNULL(myNullableField, 0)
在您的SQL查询中添加:
ISNULL(myNullableField, 0)
This makes sure that - if your value is NULL - it is converted to 0 这可以确保-如果您的值为NULL-它将转换为0
it is a select query I presume? 我认为这是一个选择查询?
在R中:
file$x[file$x=="NULL"] <- 0
Although you should fix this problem at source (ie SQL), here is one way to do it. 尽管您应该从源头(即SQL)解决此问题,但这是解决此问题的一种方法。
convert the factors to characters, then replace NA by 0 将因子转换为字符,然后将NA替换为0
I am not sure if this is right way to do for very big data though. 我不确定这是否是处理非常大数据的正确方法。
> x <- as.factor(c('1', '10', '14', '8', 'NULL'))
> y <- as.numeric(as.character(x))
Warning message:
NAs introduced by coercion
> y[is.na(y)] <- 0
> y
[1] 1 10 14 8 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.