R - Add Quotations For Elements In Vector

R Tutorial – Add Quotations Or Special Characters For Elements In Vector

Enhance your R coding with a simple function to add quotations or special characters to vector elements. Particularly useful for SQL queries in R, this feature streamlines data manipulation. The provided function, add_quotation_for_vector, allows customizable quotation marks for versatile applications in data science workflows.

Original Post

R – Add Quotations Or Special Characters For Elements In Vector


Adding quotations or special characters to elements in vector, I think this a really useful feature. Especially, if you write SQL in R, this will be handy to you. Like the examples:

# SQL
# where colname in ("R", "Python", "SQL")
vec <- c("R", "Python", "SQL")
> [1] "R" "Python" "SQL"   
vec_paste <- paste0(vec, collapse = ",")
> [1] "R,Python,SQL"
# If you paste all components directly, elements won't have their own quotations.

Copy And Paste And Use

add_quotation_for_vector <- function(input, mark = "'"){
  
  len <- length(input)
  quotation <- rep(mark, times = len)
  return_vec <- paste0(quotation, input, quotation)
  
  return(return_vec)
}
# 範例
vec <- c(123, "ABC", "D")
vec2 <- add_quotation_for_vector(vec)
> [1] "'123'" "'ABC'" "'D'" 

Recommended Posts

Learn Python And R In DataCamp. Start Your Data Science Career.

🚀 Unlock Ads-Free Experience At $5/year

14 days free trial Cancel anytime

9 thoughts on “R Tutorial – Add Quotations Or Special Characters For Elements In Vector”

Leave a Comment

Your email address will not be published. Required fields are marked *