我想写一个输出"TRUE“或"FALSE”的函数,这取决于输入是否对应于颜色的十六进制表示法。
我是一个R(和编码)的初学者,并且想出了一个基本的、不优雅的、冗长的代码想法(这不起作用……)。在几个单词中,使用strslipt(向量,split="")拆分字符串向量,然后在for循环中连续检查每个组件是否大于9或对应于不同于字母表前六个字母的字母。
ab <- strsplit(a, split="")
ab[[1]][1]
for(i in 2:nchar(a)) {
if(!is.character(a)) {
stop("invalid input; a string expectef")
}
if (ab[[1]][1] != '#') {
c <- 'FALSE'
}
if (ab[[1]][1] > '10') {
c <- 'FALSE'
}
if (ab[[1]][i] != 'A') {
c <- 'FALSE'
}
if (ab[[1]][i] != 'a') {
c <- 'FALSE'
}
if (ab[[1]][i] != 'B') {
c <- 'FALSE'
}
if (ab[[1]][i] != 'b') {
c <- 'FALSE'
}
if (ab[[1]][i] != 'C') {
c <- 'FALSE'
}
if (ab[[1]][i] != 'c') {
c <- 'FALSE'
}
if (ab[[1]][i] != 'D') {
c <- 'FALSE'
}
if (ab[[1]][i] != 'd') {
c <- 'FALSE'
}
if (ab[[1]][i] != 'E') {
c <- 'FALSE'
}
if (ab[[1]][i] != 'e') {
c <- 'FALSE')
}
if (ab[[1]][i] != 'F') {
c <- 'FALSE'
}
if (ab[[1]][i] != 'f') {
c <- 'FALSE')
}
if(c != 'FALSE') {
c <- 'TRUE'
}
return(c)
}
非常感谢你的帮助!
发布于 2018-10-29 02:29:36
您可以在grepl
中使用正则表达式。首先是一个查找两位十六进制数的简单示例,以了解以下内容:
x = c('#2A', '&33', '#e4', '#EG')
grepl('^#[0-9A-Fa-f]{2}$', x)
# [1] TRUE FALSE TRUE FALSE
它的工作原理:
^
表示模式必须位于字符串的开头。也就是说,在# are allowed#
匹配之前没有字符,所以这必须是第一个character[0-9A-F-a-f]
匹配0-9范围内的任何字符,A-F或a-f{2}
表示我们恰好需要2个这样的characters$
意味着该模式也必须在字符串的末尾-因此不允许额外的字符R中的颜色字符串必须具有6位或8位十六进制数字,具体取决于它们是否包含alpha值。所以为了寻找这两种可能性,我们可以这样做
grepl('^#[0-9A-Fa-f]{6}$', x) | grepl('^#[0-9A-Fa-f]{8}$', x)
发布于 2018-10-29 02:58:13
您可以使用以下命令:
hexa <- "#FFFFFF"
output = !(is.na(strtoi(stringr::str_sub(hexa, 2), 16L)))
output
发布于 2018-10-30 18:28:56
非常感谢你的反馈。我想我基本上想出了一个更好的解决方案的开始,使用stringr()包。下面是我的代码:
is_hex <- function(a= 'a sentence') {
if(!is.character(a)) {
stop("invalid input; a string was expected")
}
if (nchar(a) != '7') {
return(as.logical("FALSE"))
}
if (substr(a, 1,1 ) != '#') {
return(as.logical("FALSE"))
}
if (str_detect(a, pattern='[G-Z g-z]') == 'FALSE') {
result <- as.logical("TRUE")
}
else {
result <- as.logical("FALSE")
}
return(result)
}
现在我面临的问题是:
if(!is.character(a)) {
stop("invalid input; a string was expected")
}
似乎不管用。事实上,如果我评估我的函数is_hex(a='TRUE'),那么我得到的是False,而不是预期的错误。
非常感谢!
https://stackoverflow.com/questions/53037077
复制相似问题