[R] Issues with the way Apply handled NA's

David L Carlson dcarlson at tamu.edu
Mon Nov 14 22:56:50 CET 2016


This behavior is documented in the manual page:

> prod(NULL)
[1] 1

You can check for an empty vector as follows:

plabor <- structure(list(colA = c(6, NA, 3, 4), colB = c(25, NA, 2, 7), 
    colC = c(3, NA, 19, NA)), .Names = c("colA", "colB", "colC"),
    class = "data.frame", row.names = c(NA, -4L))
# Use dput() to send data to the list

plabor$colD = apply(plabor[c("colA","colB","colC")], 1, prod, na.rm=TRUE)
# Use TRUE and FALSE since the abbreviations T and F are not reserved and
# could be redefined

vals <- apply(plabor[c("colA","colB","colC")],1,function(x) length(na.omit(x)))
vals
# [1] 3 0 3 2
plabor$colD <- ifelse(vals>0, plabor$colD, NA)
plabor

#   colA colB colC colD
# 1    6   25    3  450
# 2   NA   NA   NA   NA
# 3    3    2   19  114
# 4    4    7   NA   28

-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352


-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Olu Ola via R-help
Sent: Monday, November 14, 2016 2:52 PM
To: R-help Mailing List
Subject: [R] Issues with the way Apply handled NA's

 Hello,I have a data set called plabor and have the following format:

| ColA | ColB | Colc |
| 6 | 25 | 3 |
| NA | NA | NA |
| 3 | 2 | 19 |
| 4 | 7 | NA |


I wanted to find the product of the three columns for each of the rows and I used the apply function follows:
plabor$colD = apply(plabor[c("colA","colB","colc")],1,prod,na.rm=T)
The result are as follows:

| ColA | ColB | Colc | colD |
| 6 | 25 | 3 | 450 |
| NA | NA | NA | 1 |
| 3 | 2 | 19 | 114 |
| 4 | 7 | NA | 28 |


The second row results is 1 instead of being ignored.
How do I deal with this issue because I do not want to exclude these data points with all NA's?
Regards

	[[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


More information about the R-help mailing list