我想反转一个字符串但不影响数字。 例如:
输入:“ abcdef 123” 输出:“ fedcba 123”
在我使用此功能的那一刻,它会影响所有字符:
name<-sapply(strsplit(name, split = ""),
function(str) {paste(rev(str), collapse = "")})
答案 0 :(得分:1)
可靠的解决方案:
# convert vector of strings into list of vectors of words
words = strsplit(name, ' ', fixed = TRUE)
str_rev = sapply(words, function(x) {
# we know some warnings may be created, ignore them
suppressWarnings({
is_num = !is.na(as.numeric(x))
})
# reverse non-numeric elements
str_words = strsplit(x[!is_num], "", fixed = TRUE)
x[!is_num] = sapply(str_words, function(y) {
paste(rev(y), collapse = "")
})
paste(x, collapse = ' ')
})
这允许该规则适用于更普遍的情况,在这些情况下您不知道数字“单词”将出现在哪里,并且name
作为向量:
name = c("abcdef 123", 'abc def 123', 'abc 123 def')
str_rev
# [1] "fedcba 123" "cba fed 123" "cba 123 fed"
答案 1 :(得分:1)
这是一个利用stri_reverse
中的stringi
的选项
library(stringi)
library(gsubfn)
gsubfn("([^0-9 ]+)", ~ stri_reverse(x), name)
#[1] "fedcba 123" "cba fed 123" "cba 123 fed"
或为@G。提到Grothendieck,可以删除匿名函数调用
gsubfn("([^0-9 ]+)", stri_reverse, name)
name <- c("abcdef 123", 'abc def 123', 'abc 123 def')
答案 2 :(得分:0)
这是一种方法:
案例1:
a <- "abcdef 123"
# split the string
split_a <- unlist(strsplit(a, " "))
# reverse it
paste(paste(rev(strsplit(split_a[1],'')[[1]]), collapse = ''), split_a[2])
"fedcba 123"
案例2:
a <- "abc def 123"
# split the string
split_a <- unlist(strsplit(a, " "))
# removing the last word
to_split <- split_a[-length(split_a)]
reversed <- paste(sapply(lapply(strsplit(to_split, NULL), rev), paste, collapse=''), collapse=' ')
final <- paste(reversed, split_a[length(split_a)], collapse=" ")
[1] "cba fed 123"