我查询数据库以创建用于绘图的数据框,我的一个数据转换需要数学运算,因此我需要将特定列的空条目改为零。但是,我无法获取要替换的空值。
这是一个示例输出与预期输出:
Actual:
income travel_spending sports_leisure_spending gender percent_travel
1 25 33 NA M 1.32000000
2 357 136 NA M 0.38095238
3 25 18 5 M 0.72000000
4 51 527 NA M 10.33333333
5 51 527 NA F 10.33333333
6 48 4 60 F 0.08333333
Expected:
income travel_spending sports_leisure_spending gender percent_travel
1 25 33 0 M 1.32000000
2 357 136 0 M 0.38095238
3 25 18 5 M 0.72000000
4 51 527 0 M 10.33333333
5 51 527 0 F 10.33333333
6 48 4 60 F 0.08333333
这是我的代码。有问题的专栏是sports_leisure_spending:
query <- 'SELECT income, REPLACE(travel_spending, "33", "33") AS travel_spending,
CASE sports_leisure_spending WHEN "NA" THEN "0" ELSE sports_leisure_spending END AS sports_leisure_spending,
gender, CAST(travel_spending AS float)/CAST(income AS float) AS percent_travel FROM customer'
我还尝试了以下方法:
REPLACE(sports_leisure_spending, "NA", "0") -> does nothing
REPLACE(sports_leisure_spending, NA, "0") -> does nothing
REPLACE(sports_leisure_spending, NULL, "0") -> makes EVERYTHING NA
REPLACE(sports_leisure_spending, "", "0") -> does nothing