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!
Such function exist already:
library(glue)
name My name is Fred.
LikeLike
[…] by data_admin [This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page […]
LikeLike
Is there some reason why it can’t be done this way?
vv <- 'tomaz'
cat('This is text by: ', vv, ' and today is a great day!\n',sep='')
(or use double quotes if preferred)
LikeLike