R中的字符串比较
我正在尝试比较R中的两个字符串。请建议如何比较下面R代码中的n和反向_拆分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
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")