我想编写一个函数,根据输入是否对应颜色的十六进制表示法,输出“ TRUE”或“ FALSE”。
我是R(和编码)的初学者,并提出了一个基本的,不雅致且冗长的代码思想(这是行不通的...)。简而言之,用strslipt(vector,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)
}
非常感谢您的帮助!
答案 0 :(得分:1)
您可以在grepl
中使用正则表达式。首先是一个简单的示例,该示例寻找两位数字的十六进制,以了解这一点:
x = c('#2A', '&33', '#e4', '#EG')
grepl('^#[0-9A-Fa-f]{2}$', x)
# [1] TRUE FALSE TRUE FALSE
工作原理:
^
表示模式必须在字符串的开头。即,不允许在#之前输入任何字符#
与其自身匹配,因此该字符必须是第一个字符[0-9A-F-a-f]
匹配0-9,A-F或a-f范围内的任何字符{2}
意味着我们恰好需要2个这样的字符$
表示模式也必须位于字符串的末尾-因此不允许使用其他字符R中的颜色字符串必须具有6或8个十六进制数字,具体取决于它们是否包含alpha值。因此,寻找这两种可能性,我们可以做到
grepl('^#[0-9A-Fa-f]{6}$', x) | grepl('^#[0-9A-Fa-f]{8}$', x)
答案 1 :(得分:0)
您可以使用此:
hexa <- "#FFFFFF"
output = !(is.na(strtoi(stringr::str_sub(hexa, 2), 16L)))
output
答案 2 :(得分:0)
非常感谢这些反馈。我认为我基本上是使用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而不是预期的错误。
非常感谢!