Pradeep
Pradeep

Reputation: 565

How to use value of variables in expressions in R?

I am relatively new to R. How do I use the value of variables in print and other statements. For example, in Java we can do this by:

System.out.println(" My name is "+ pradeep);

We use the + operator. How to do this in R?

Upvotes: 4

Views: 953

Answers (3)

G. Grothendieck
G. Grothendieck

Reputation: 269664

Assuming

pradeep <- "Pradeep"

Try this:

cat("My name is", pradeep, "\n")

Also the gsubfn package has the ability to add quasi perl-style string interpolation to any command by prefacing the command with fn$

library(gsubfn)
fn$cat("My name is $pradeep\n")

fn$print("My name is $pradeep")

There is also sprintf and paste, as mentioned by others.

Upvotes: 1

Richie Cotton
Richie Cotton

Reputation: 121077

In general you should prefer Henrik's answer, but note that you can specify strings with sprintf.

name <- c("Richie", "Pradeep")
sprintf("my name is %s", name)

Upvotes: 1

Henrik
Henrik

Reputation: 14450

In R you can do this with paste() (see ?paste for more info):

print(paste("My name is ", pradeep, ".", sep = ""))

Upvotes: 3

Related Questions