根据字母创建数字向量

问题描述 投票:0回答:2

所以,这是问题:

“创建一个给定单词的函数,返回位置字母向量上的单词字母集合例如,如果单词为“ abba”,该函数将返回1 2 2 1。“

到目前为止,我所拥有的是:

l <- function(word) {
    chr <- c()
    y <- c()
    strsplit(chr,word)
    i<-1
    while(i<length) {
           o<-letters[i]
           x<-chr[i]
           if(o==x) {
                    y[i]<-i
           }
           i+1
    }
    y
}

我已经尝试运行l(“ hello”),它返回NULL。我很失落,不胜感激!谢谢!

r
2个回答
1
投票

使用base R

lapply(strsplit(x, "", fixed = TRUE), function(x) match(x, letters))

[[1]]
[1] 1 2 2 1

0
投票
library(purrr)
my_fun <- function(x) {
  x %>% 
    strsplit("") %>% 
    map(factor, levels = letters) %>% 
    map(as.numeric)
}


x <- c("abba", "hello")
my_fun(x)
#> [[1]]
#> [1] 1 2 2 1
#> 
#> [[2]]
#> [1]  8  5 12 12 15
© www.soinside.com 2019 - 2024. All rights reserved.