Function Modifying a Character String

岁酱吖の 提交于 2019-12-20 03:10:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!