Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Dec 17th, 2012  |  syntax: None  |  size: 0.68 KB  |  views: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. foo <- LETTERS[1:4]
  2. foo[4] <- NA
  3. foo
  4. [1] "A" "B" "C" NA
  5. paste(1:4, foo, sep = ", ")
  6.        
  7. [1] "1, A"  "2, B"  "3, C"  "4, NA"
  8.        
  9. [1] "1, A" "2, B" "3, C" "4"
  10.        
  11. sub(', NA$', '', paste(1:4, foo, sep = ", "))
  12. [1] "1, A" "2, B" "3, C" "4"
  13.        
  14. paste2 <- function(...,sep=", ") {
  15.     L <- list(...)
  16.     L <- lapply(L,function(x) {x[is.na(x)] <- ""; x})
  17.     gsub(paste0("(^",sep,"|",sep,"$)"),"",
  18.                 gsub(paste0(sep,sep),sep,
  19.                      do.call(paste,c(L,list(sep=sep)))))
  20. }
  21. foo <- c(LETTERS[1:3],NA)
  22. bar <- c(NA,2:4)
  23. baz <- c("a",NA,"c","d")
  24. paste2(foo,bar,baz)
  25. # [1] "A, a"    "B, 2"    "C, 3, c" "4, d"
  26.        
  27. gsub(", $", "", paste(1:4, ifelse(is.na(foo), "", foo), sep = ", "))
clone this paste RAW Paste Data