Little useless-useful R functions – Inserting variable values into strings
This article is originally published at https://tomaztsql.wordpress.com
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!
Thanks for visiting r-craft.org
This article is originally published at https://tomaztsql.wordpress.com
Please visit source website for post related comments.