I have input data from SQL which has fields that are the string "NULL", such that
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().
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.
If you're reading this in with read.csv
, set the option na.strings='NULL'
. This will import file$x
as numeric
, instead of factor
, with numeric NA
s objects in place of the NULL
strings. Then to replace NA
s with 0
s:
file$x[is.na(file$x)] <- 0
In your SQL Query add: ISNULL(myNullableField, 0)
This makes sure that - if your value is NULL - it is converted to 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.
convert the factors to characters, then replace NA by 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.