-3

I have a dataframe df, and it has a column col of character() type. Columns are filled by Sql Query results. Sometimes sql query returns empty set. If col is empty, I want to set it to NA. How I can achieve that?

Assume this: I'm assigning currently col <- select 1 from Table (returns empty set). If col is empty, I want to set it to NA

col
[1] result
<0 rows> (or 0-length row.names)
rakamakafo
  • 1,144
  • 5
  • 21
  • 44
  • 1
    When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Feb 12 '18 at 22:06
  • @MrFlick I can't make reproducible example, since I don't expect community to install SQL Server instance , and I think it's pretty clear question. Regards – rakamakafo Feb 12 '18 at 22:11

1 Answers1

2

Hard to tell exactly what you are looking for, but:

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"
Mark White
  • 1,228
  • 2
  • 10
  • 25