我有很多这样的字符串:
NewImage": {
"likes": {
"N": "5"
},
"is_em": {
"B": "ZWFzdXJlLg=="
},
"id": {
"N": "9"
},
"user_access_key_id": {
"S": "ASIAJIGCYGKAOSMJN6MA"
}
}
我想将它们转换为具有以下特征的句子:
所以这些字符串上面的字符串应该像这样打印:
x1 <- c("Red", "Green", "Blue")
x2 <- c("Red", "Green", "Orange", "Yellow", "Pink")
x3 <- c("Red", "Green")
x4 <- c("Red")
x5 <- c("Red", "Green", "Orange", "Yellow", "Pink", "Blue", "Green")
我开始做一个功能来实现上述目标,这是我得到了多远:
# red, green and blue
# red, green, orange, yellow and pink
# red and green
# red
# red, green, orange, yellow, pink, blue and green
但无法弄清楚如何实现我想要的输出。有人可以帮忙吗?
答案 0 :(得分:3)
仅使用基础R:
sentence_string <- function(x){
l <- length(x)
if (l == 1) {
tolower(x)
} else {
x <- tolower(x)
y <- paste(x[-l], collapse = ', ')
paste0(c(y, x[l]), collapse = ' and ')
}
}
,并提供:
> sentence_string(x1)
[1] "red, green and blue"
> sentence_string(x2)
[1] "red, green, orange, yellow and pink"
> sentence_string(x3)
[1] "red and green"
> sentence_string(x4)
[1] "red"
> sentence_string(x5)
[1] "red, green, orange, yellow, pink, blue and green"
答案 1 :(得分:2)
我喜欢使用stringi
进行这些操作,
library(stringi)
get_string <- function(x){
y <- paste(x, collapse = ', ')
y1 <- tolower(stri_replace_last_regex(y, ',', ' and'))
return(y1)
}
get_string(x1)
#[1] "red, green and blue"