所以,这是一个问题:
“创建一个给定一个单词的函数,返回单词的字母在字母向量上的位置。例如,如果单词是‘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。我很迷茫,希望能得到任何帮助!谢谢!
发布于 2019-10-30 13:17:19
使用base R
lapply(strsplit(x, "", fixed = TRUE), match, letters)
[[1]]
[1] 1 2 2 1
发布于 2019-10-30 13:27:45
我在base
中提供了另一个有趣的函数
x <- "abcxyz"
strtoi(strsplit(x, "")[[1]], 36) - 9
# [1] 1 2 3 24 25 26
strtoi()
将以n为基数的数制转换为以十进制为基数的(decimal)数制。以基数为16的(即hexadecimal) )为例,strtoi("12", base = 16)
将得到18
,因为十六进制的12是十进制的18。如果base为36,strtoi()
会将(1~9,a~z)映射到1~35,即a~z在base-36系统中是十进制的10~35。我的代码中的-9
将把10~35转换成1~26,这是OP所需要的。另一个常见的用途是将二进制数转换为十进制。例如,strtoi("01001", base = 2)
得到9分。
发布于 2019-10-30 13:14:23
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
在这里,我们使用因子是引擎盖下的整数。
假设str
是一个字符向量,例如str <- c('a', 'b', 'b', 'a')
。当我们运行factor(str, levels = letters)
时,我们将其转换为一个具有26个级别的因子:'a','b','c‘等等。如果我们对它应用as.integer
,a
将变成1,因为它是第一级,'b‘-2等等。
https://stackoverflow.com/questions/58626139
复制