考虑下面的data.frame:
df <- structure(list(sufix = c("atizado", "atoria", "atório", "auta",
"áutico", "ável"), min_stem_len = c(4, 5, 3, 5, 4, 2), replacement = c("",
"", "", "", "", ""), exceptions = list(character(0), character(0),
character(0), character(0), character(0), c("afável", "razoável",
"potável", "vulnerável"))), .Names = c("sufix", "min_stem_len",
"replacement", "exceptions"), row.names = 21:26, class = c("tbl_df",
"tbl", "data.frame"))
我在此data.frame的变量sufix
中有一个字符串列表。
现在我有一个单词word <- "amável"
,我希望得到这个单词的sufix与df$sufix
的每个单词的长度相同。
我正在使用以下代码:
library(stringr)
word <- "amável"
str_sub(word, start = -stringr::str_length(df$sufix))
但这会输出:
> str_sub(word, start = -stringr::str_length(df$sufix))
[1] "amável" "mável" "mável" "vel" "mável" "vel"
> df$sufix
[1] "atizado" "atoria" "atório" "auta" "áutico" "ável"
我期待结果向量的最后一个元素是“ável”,因为:
> str_length("ável")
[1] 4
> str_sub(word, start = -4)
[1] "ável"
这是一个更简单的可重复示例:
set.seed(100)
a <- sample(1:10, 10000, replace = T)
res <- rep("ábc", 10000) %>% str_sub(start = -a)
sum(ifelse(a > 3, 3, a) != str_length(res))
[1] 2504
答案 0 :(得分:1)
如果您注意到,所有结果都是错误的(第一个除外)。
他们应该是
[1] "amável" "amável" "amável" "ável" "amável" "ável"
这可以通过
轻松解决library(stringi)
stri_sub(rep(word, 6), from = -stri_length(df$suffix))
我打赌你可以重复使用stringr
代码。
###编辑添加###
我现在明白你的意思了。绝对存在一种奇怪的行为,很可能是特殊角色á
。请参阅以下示例:
df <- data.frame(suffix = c("Lorem","ipsum","dolor","sit","amet","consectetur","adipiscing", "elit","Donec","arcu"))
df$len <- stri_length(df$suffix)
然后看看结果的第7个元素中的奇怪行为:
stri_sub("amavel", from = -df$len)
## [1] "mavel" "mavel" "mavel" "vel" "avel" "amavel" "amavel" "avel"
## [9] "mavel" "avel"
# Compared to
stri_sub("amável", from = -df$len)
## [1] "mável" "mável" "mável" "vel" "ável" "amável" "mável" "ável"
## [9] "mável" "ável"
很奇怪,如果使用rep
,结果会在最后一种情况下得到纠正:
stri_sub(rep("amável", 10), from = -df$len)
## [1] "mável" "mável" "mável" "vel" "ável" "amável" "amável" "ável"
## [9] "mável" "ável"
# note how the 7th element is now correct.
所以即使它有点hacky,上面提供的解决方案应该可行。
我尝试查看stri_sub
的代码,它引用了C_stri_sub
,但这对我来说是一个死胡同。也许有人更了解C
和/或字符串操作可以来帮忙吗?
### SECOND EDIT ###
在我看来问题是在stri_sub
的调用中重复了字符串。查看您在编辑中添加的替代代码:
set.seed(100)
a <- sample(1:10, 10000, replace = TRUE)
res <- stri_sub(rep("ábc", 10000), from = -a)
sum(ifelse(a > 3, 3, a) != stri_length(res))
## [1] 0
答案 1 :(得分:1)
已在TaskCanceledException
的开发分支中修复此问题,请参阅https://github.com/gagolews/stringi/issues/227(来自stringi
的{{1}}依赖于str_sub
stringr
)。一旦CRAN上有可用的更新,任何来自“普通公众”的人都可以复制正确的行为,而不是:
stri_sub