如果dataframe列为空,则分配NA

时间:2018-02-12 22:06:08

标签: r

我有一个数据帧df,它的列col为character()类型。列由SQL查询结果填充。有时sql查询返回空集。 如果col为空,我想将其设置为NA。我怎么能做到这一点?

假设:我从表中指定col< - select 1(返回空集)。如果col为空,我想将其设置为NA

col
[1] result
<0 rows> (or 0-length row.names)

1 个答案:

答案 0 :(得分:2)

很难准确说出你在寻找什么,但是:

if (nrow(result) == 0) {
  NA
} else {
  result$col
}
> result <- data.frame(col = c())
> if (nrow(result) == 0) {
+   NA
+ } else {
+   result$col
+ }
[1] NA

> result <- data.frame(col = letters, stringsAsFactors = FALSE)
> if (nrow(result) == 0) {
+   NA
+ } else {
+   result$col
+ }
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" "u" "v" "w" "x" "y" "z"