1

I have the following vector:

vector1 <- c("A", "B", "C" , NA, NA, "D")

I want to apply this function paste ignoring NA values in vector1

vector2 <- paste("#", vector1, "something", sep = "")

and obtain this

vector2 <- c("#Asomething", "#Bsomething" , "#Csomething", NA, NA, "#Dsomething")

I want to avoid ex-post solutions using sub where I just get rid of elements containing the letters "NA" in the string.

I saw a similar question: suppress NAs in paste() however there they want to ignore NA and simply paste #something whereas I want NA to be displayed.

mnist
  • 6,571
  • 1
  • 18
  • 41
Carbo
  • 906
  • 5
  • 23

3 Answers3

2

Base R solution:

vector2 <- ifelse(is.na(vector1), NA_character_, paste("#", vector1, "something" ,sep = ""))
hello_friend
  • 5,682
  • 1
  • 11
  • 15
  • Did not see your answer which is pretty much the same. Why do you use `NA_character_` and not just `NA`? –  May 04 '20 at 11:42
  • @machine NA is of type logical, NA_character is of type character. vector_1 is a character vector, vector_2 is also explicitly a character vector. – hello_friend May 04 '20 at 11:44
  • But isn't it another vector than the OP asked for? `c("#Asomething", "#Bsomething" , "#Csomething" ,NA , NA, "#Dsomething")` –  May 04 '20 at 11:45
  • @machine No. Its a matter of typing. As in, the data.type of the vector, explicitly typing prevents any problems of unintended type conversion; in this instance an unintended consquence may be conversion to a factor vetor, when OP wants a character vector. – hello_friend May 04 '20 at 12:32
  • I see. +1 from me! Did not know that it is possible to define NA in a certain class. –  May 04 '20 at 13:36
  • @machine no worries, cheers ! Yes NA alone is of type logical ! Also interesting discussion on the negatives of the tidyverse post, post should not have been marked as duplicate! – hello_friend May 04 '20 at 13:37
2

You can combine it with ifelse like this

ifelse(is.na(vector1), NA, paste("#", vector1, "something" ,sep = ""))

Although this was marked as answered please also see the answer of @hello_friend which may be more appropriate.

1

I think you need to use sapply() with a anonymous function.

Please, have a look at the following code which does what you want.

vector1 <- c("A", "B" , "C" ,NA_character_ , NA_character_, "D")
vector2 <- sapply( vector1, function( x ) 
  ifelse( is.na( x ), 
          NA_character_, 
          paste("#", x, "something" ,sep = "") ),
  USE.NAMES = FALSE
)
vector2
#> [1] "#Asomething" "#Bsomething" "#Csomething" NA            NA           
#> [6] "#Dsomething"

Created on 2020-05-04 by the reprex package (v0.3.0)

Francesco Grossetti
  • 1,555
  • 9
  • 17