celestialgod

combining row with removing NAs

Aug 10th, 2015
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 0.87 KB | None | 0 0
  1. N = 50000
  2. x = y = rep(NA, N)
  3. x[sample(N, N/2)] = rnorm(N/2)
  4. y[is.na(x)] = rnorm(N/2)
  5. dat = data.frame(x, y)
  6.  
  7. f1 = function(dat){dat$z = dat$x; dat$z[is.na(dat$x)] = dat$y[is.na(dat$x)]; dat}
  8. f2 = function(dat){dat$z = ifelse(is.na(dat$x), dat$y, dat$x); dat}
  9. f3 = function(dat){dat$z = with(dat, ifelse(is.na(x), y, x)); dat}
  10. f4 = function(dat){dat$z = na.omit(c(unlist(t(dat)))); dat}
  11. f5 = function(dat){dat$z = rowSums(dat, TRUE); dat}
  12.  
  13. library(rbenchmark)
  14. benchmark(f1(dat), f2(dat), f3(dat), f4(dat), f5(dat),
  15.   columns = c("test", "replications", "elapsed", "relative"),
  16.     order = "relative", replications = 20)
  17. #      test replications elapsed relative
  18. # 5 f5(dat)           20    0.28    1.000
  19. # 1 f1(dat)           20    0.30    1.071
  20. # 4 f4(dat)           20    0.40    1.429
  21. # 2 f2(dat)           20    0.46    1.643
  22. # 3 f3(dat)           20    0.58    2.071
Advertisement
Add Comment
Please, Sign In to add comment