Guest User

Untitled

a guest
Apr 24th, 2012
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. In R, is there a way to handle NA in an integer column of a data.frame so that NA values are not included when subseting?
  2. (t=structure(list(count = c(NA, 2, NA, NA, NA, 8, NA, NA, NA)), .Names = "count", row.names = c(NA,-9L), class = "data.frame"))
  3. count
  4. 1 NA
  5. 2 2
  6. 3 NA
  7. 4 NA
  8. 5 NA
  9. 6 8
  10. 7 NA
  11. 8 NA
  12. 9 NA
  13.  
  14. > t[t$count>=1,]
  15. [1] NA 2 NA NA NA 8 NA NA NA
  16.  
  17. > t[t$count>=1&!is.na(t$count),]
  18. [1] 2 8
  19.  
  20. transform(t, replace all NAs from count columns with 0)
  21.  
  22. transform(t, replace all NA from all numeric columns with 0 in t)
  23.  
  24. > t[ which(t$count >= 1), ]
  25. [1] 2 8
  26. # Or if you still want a dataframe result
  27. > t[ which(t$count >= 1), , drop=FALSE]
  28. count
  29. 2 2
  30. 6 8
  31.  
  32. > t[ -which(t$count < 1), , drop=FALSE]
  33. [1] count
  34. <0 rows> (or 0-length row.names)
  35. > t[ which(t$count < 1), , drop=FALSE]
  36. [1] count
  37. <0 rows> (or 0-length row.names)
  38.  
  39. t$count[is.na(t$count)] <- something.else
  40.  
  41. dt = as.data.table(t)
  42. t[count>=1] # NA's are treated as FALSE
Advertisement
Add Comment
Please, Sign In to add comment