【发布时间】:2013-12-27 05:04:35
【问题描述】:
我需要一个函数,它将输入作为字符串(空白)并打印出以下内容:
"Hello BLANK World"
即,world("seven") 打印出"Hello seven World"
我对如何在 R 中处理字符串感到非常困惑。
【问题讨论】:
我需要一个函数,它将输入作为字符串(空白)并打印出以下内容:
"Hello BLANK World"
即,world("seven") 打印出"Hello seven World"
我对如何在 R 中处理字符串感到非常困惑。
【问题讨论】:
你想要函数paste
world <- function(x) paste("Hello", x, "World")
【讨论】:
paste 是第一个了解字符串操作的函数。
或者……
x <- "seven"
sprintf("Hello %s World", x)
换句话说,不需要world 函数,因为sprintf 就是这样做的。
【讨论】:
在 R here 中有一个使用字符串的教程。
R 没有像许多其他语言那样的“连接”运算符。比如:
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"
正如@Matthew 所说,您必须使用paste(...) 进行连接。不过,请阅读有关默认分隔符的文档。
【讨论】:
"+.String" <- function(e1, e2) paste0(e1, e2); "+.String" <- function(e1, e2){paste0(e1,e2)}; as.String("hey ") + as.String("you")
as.String <- function(x){class(x) <- "String"; x}
stringi 包:)
使用stringi 包:
require(stringi)
## Loading required package: stringi
"a"%+%"b"
## [1] "ab"
【讨论】: