Little useless-useful R functions – Inserting variable values into strings
[This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Another useless function that could be found in many programming languages. For example typical Python sample, that everyone have encountered would be:
MyName = "Tomaz" Value_in_string = "My Name is {} and I write this post.".format(MyName) print(Value_in_string)
Resulting in a string with:
My Name is Tomaz and I write this post.
So, let’s do something similar in R. We will call this function is cat_v and in most useless way, it looks like:
cat_v <- function(tex){ rr <- " " pos_1 <- which(strsplit(tex, "")[[1]]=="{") pos_2 <- which(strsplit(tex, "")[[1]]=="}") end_pos <- nchar(tex) varname <- substr(tex, pos_1+1, pos_2-1) t <- get(eval(varname)) t1 <- substr(tex, 1, pos_1-1) t2 <- substr(tex, pos_2+1, end_pos) t1 <- paste0(t1, t, t2) cat(t1) }
Same as with Python, we can do now this with R in same fashion.
# Creating a variable vv <- "tomaz" # Running cat function with variable cat_v("This is text by: {vv} and today is a great day!") cat_v("This is text by: {vv}")
And result is pretty obvious:
As always, code is available in at the Github in same Useless_R_function repository.
Happy R-coding!
To leave a comment for the author, please follow the link and comment on their blog: R – TomazTsql.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.