Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中的字符串比较_R - Fatal编程技术网

R中的字符串比较

R中的字符串比较,r,R,我正在尝试比较R中的两个字符串。请建议如何比较下面R代码中的n和反向_拆分 n= readLines(file("stdin")) string <- strsplit(as.character(n), "") string = unlist(string) reversed_split = string[nchar(n):1] if(string == reversed_split) print("Indeed") else print("Not At All") n=readL

我正在尝试比较R中的两个字符串。请建议如何比较下面R代码中的n和反向_拆分

n= readLines(file("stdin"))
string <- strsplit(as.character(n), "")
string = unlist(string)
reversed_split = string[nchar(n):1]

if(string == reversed_split)
 print("Indeed")
else
 print("Not At All")
n=readLines(文件(“stdin”))

字符串您不能在
if()
语句中比较两个向量
if()
接受单个
TRUE
FALSE
条件。您可以添加
all()
函数,它将工作:

n <- c("madam" )
string <- strsplit(as.character(n), "")
string = unlist(string)
reversed_split = string[nchar(n):1]

if (all(string == reversed_split) )  print("Indeed") else print("Not At All")
您可能会发现使用库
stringi
很有用:

library(stringi)
stri_reverse("madam")
## [1] "madam"
stri_reverse("sir")
## [1] "ris"
您可以使用package中的函数来帮助比较字符向量,该函数返回可在条件语句中使用的
TRUE
FALSE

ifelse(identical(c("a", "s"), c("a", "s")), "Indeed", "Not At All")
# Your question could be solved as:
ifelse(identical(string, reversed_split), "Indeed", "Not At All")

请您将您的问题与一些示例分享……
if(all(string==reversed\u split))
。您需要在
if
语句中打开和关闭
{
}
。另外,使用
n
ifelse(identical(c("a", "s"), c("a", "s")), "Indeed", "Not At All")
# Your question could be solved as:
ifelse(identical(string, reversed_split), "Indeed", "Not At All")