Reputation: 465
I need a function that will take input as a character string (BLANK) and print out the following:
"Hello BLANK World"
i.e., world("seven") prints out "Hello seven World"
I'm very confused on how to work with character strings in R.
Upvotes: 2
Views: 213
Reputation: 16080
Use stringi
package:
require(stringi)
## Loading required package: stringi
"a"%+%"b"
## [1] "ab"
Upvotes: 0
Reputation: 59345
There's a tutorial on working with character strings in R here.
R does not have a "concatenate" operator as many other languages do. So for example:
x <- "A"
y <- "B"
x + y # Like javascript? No - does NOT produce "AB"
# Error in x + y : non-numeric argument to binary operator
x || y # Like SQL? No - does NOT produce "AB"
# Error in x || y : invalid 'x' type in 'x || y'
x . y # Like PHP? No - does NOT produce "AB"
# Error: unexpected symbol in "x ."
paste(x,y, sep="")
# [1] "AB"
As @Matthew says, you must use paste(...)
to concatenate. Read the documentation, though, about default separators.
Upvotes: 4
Reputation: 109844
Or...
x <- "seven"
sprintf("Hello %s World", x)
In other words no need for a world
function as that's what sprintf
does.
Upvotes: 5
Reputation: 42639
You want the function paste
world <- function(x) paste("Hello", x, "World")
Upvotes: 5