R库(sqldf)不能使用na(null)更改列的包含

时间:2018-07-12 07:37:56

标签: r sqldf

我有一列,我想在使用

时用一个值替换空值(该列仅包含na)。
library(sqldf)
options(sqldf.driver = "SQLite")
var1<-sqldf("select col1, case when col2 is \"NA\" then 'sth' else 'sth' end as col2 from table1")

它没有改变任何东西,我也尝试过

 var1<-sqldf("select col1, case when col2 is null then 'sth' else 'sth' end as col2 from table1")

并简单地尝试全部替换(整个列为null):

var1<-sqldf("select col1, 'sth'as col2 from table1")

不是这些工作,为了使其正常工作,我必须创建一个新列,例如

var1<-sqldf("select col1, 'sth'as col2_sth from table1") 

但是我需要保留该列的新值,在这种情况下我该怎么办?这是sqldf中的错误吗?

1 个答案:

答案 0 :(得分:1)

如果您所有的列均为不适用,则可能是您的问题在于该列为数字,并且您不能在不更改类的情况下输入字符,请参见示例:

library(sqldf)
options(sqldf.driver = "SQLite")
table1 <- data.frame(col1 = 1:6, col2 = rep(NA, 6))

sqldf("select col1, case when col2 is NULL then 'sth' else 'sth' end as col2 from table1")
  col1 col2
1    1   NA
2    2   NA
3    3   NA
4    4   NA
5    5   NA
6    6   NA
Warning message:
In asfn(rs[[i]]) : NAs introduced by coercion

更改col2的类可以正常工作。

table1$col2 <- as.character(table1$col2)
sqldf("select col1, case when col2 is NULL then 'sth' else 'sth' end as col2 from table1")
  col1 col2
1    1  sth
2    2  sth
3    3  sth
4    4  sth
5    5  sth
6    6  sth
相关问题