计算名称编号

时间:2014-12-26 15:47:01

标签: r

我想计算一组给定名称的名称编号。

名称编号是通过将分配给每个字母表的值相加来计算的。值如下:

a=i=j=q=y=1
b=k=r=2
c=g=l=s=3
d=m=t=4
h=e=n=x=5
u=v=w=6
o=z=7
p=f=8

示例:David的名称编号可以按如下方式计算:

D+a+v+i+d
4+1+6+1+4
16=1+6=7

大卫的姓名是7。

我想在R中编写一个函数来执行此操作。 我很感谢我应该研究的任何指示或提示或包装建议。

3 个答案:

答案 0 :(得分:10)

此代码段将实现您的目标:

# Name for which the number should be computed.
name <- "David"

# Prepare letter scores array. In this case, the score for each letter will be the array position of the string it occurs in.
val <- c("aijqy", "bkr", "cgls", "dmt", "henx", "uvw", "oz", "pf")

# Convert name to lowercase.
lName <- tolower(name)             

# Compute the sum of letter scores.
s <- sum(sapply(unlist(strsplit(lName,"")), function(x) grep(x, val)))

# Compute the "number" for the sum of letter scores. This is a recursive operation, which can be shortened to taking the mod by 9, with a small correction in case the sum is 9.
n <- (s %% 9)
n <- ifelse(n==0, 9, n)

&#39; N&#39;是您想要的任何名称&#39;

的结果

答案 1 :(得分:6)

您需要按字母顺序创建值向量,然后使用match获取其索引。像这样:

a <- i <- j <- q <- y <- 1
b <- k <- r <- 2
c <- g <- l <- s <- 3
d <- m <- t <- 4
h <- e <- n <- x <- 5
u <- v <- w <- 6
o <- z <- 7
p <- f <- 8

vals <- c(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z)
sum(vals[match(c("d","a","v","i","d"), letters)])

答案 2 :(得分:5)

我确定有几种方法可以做到这一点,但这是一种使用命名向量的方法:

x <- c(
  "a"=1,"i"=1,"j"=1,"q"=1,"y"=1,
  "b"=2,"k"=2,"r"=2,
  "c"=3,"g"=3,"l"=3,"s"=3,
  "d"=4,"m"=4,"t"=4,
  "h"=5,"e"=5,"n"=5,"x"=5,
  "u"=6,"v"=6,"w"=6,
  "o"=7,"z"=7,
  "p"=8,"f"=8)
##
name_val <- function(Name, mapping=x){
  split <- tolower(unlist(strsplit(Name,"")))
  total <-sum(mapping[split])
  ##
  sum(as.numeric(unlist(strsplit(as.character(total),split=""))))
}
##
Names <- c("David","Betty","joe")
##
R> name_val("David")
[1] 7
R> sapply(Names,name_val)
David Betty   joe 
    7     7     4