3

I have a zoo object which contains some NA values within it and I am writing it to an Excel file using the write.xlsx command from the xlsx package. However instead of giving NA in the Excel file where required it provides #N/A which Excel has trouble working with. Is this normal behaviour? If so, is there anyway around this?

Here is an example

y <- zoo(c(1:40), as.Date(1:40))
y[20] <- NA
write.xlsx(y, file = "test.xlsx")

Many thanks

Jonno Bourne
  • 1,931
  • 1
  • 22
  • 45
wrahman
  • 123
  • 1
  • 10
  • #N/A is what excel uses as NA values. if you type "=ISNA(#N/A)" into a cell it will return TRUE. are there any other details you can provide to make your error reproducible? http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Jonno Bourne Oct 19 '16 at 08:37
  • Apologies, then it appears the function was working right and I misunderstood excel. The problem is that once it is in Excel when I try to get the average of a row the #N/A causes errors. Previously, I had a CSV file that contained NA instead of #N/A and when I would take the average of the rows Excel would ignore the NA's in the calculation. In an XLSX file it appears that this is not the case and the result of calling the AVERAGE function is also #N/A if your data range contains any NA's – wrahman Oct 19 '16 at 08:45
  • I now see the xlsx files will also ignore NA values in calculations like I had before, but not #N/A values. So I guess I am now trying to determine how I would get write.xlsx to input NA instead of #N/A. Will add a better example in the comments – wrahman Oct 19 '16 at 08:54

2 Answers2

2

This can be done either by using R or Excel

Using the xlsx package, you can leave NA values as blank cells

 write.xlsx(y, file = "test.xlsx", showNA=FALSE)

Using excel you can ignore the NA values. Remember to press ctrl +shift+enter

{=SUM(IF(ISNA(A3:D3),0,A3:D3))}
Jonno Bourne
  • 1,931
  • 1
  • 22
  • 45
1

I have to import data out of Excel and into R and then back again frequently. Our standard for an empty cell in Excel is NA. In order to avoid getting the #N/A, I used a simple workaround so I would not have to change it in Excel (Ctrl+H and replace #N/A with NA on the workbook).

Try this in R before exporting to Excel:

y[is.na(y)] <- "NA"

Excel will not know the difference between an actual NA and a char string "NA".

tdy
  • 36,675
  • 19
  • 86
  • 83