问题
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.
回答1:
You want the function paste
world <- function(x) paste("Hello", x, "World")
回答2:
Or...
x <- "seven"
sprintf("Hello %s World", x)
In other words no need for a world function as that's what sprintf does.
回答3:
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.
回答4:
Use stringi package:
require(stringi)
## Loading required package: stringi
"a"%+%"b"
## [1] "ab"
来源:https://stackoverflow.com/questions/20481621/function-modifying-a-character-string