输出一个字符串作为句子

时间:2017-01-11 14:36:21

标签: r string

我有很多这样的字符串:

NewImage": {
  "likes": {
    "N": "5"
  },
  "is_em": {
    "B": "ZWFzdXJlLg=="
  },
  "id": {
    "N": "9"
  },
  "user_access_key_id": {
    "S": "ASIAJIGCYGKAOSMJN6MA"
  }
}

我想将它们转换为具有以下特征的句子:

  1. 小写
  2. "和"分离倒数第二个和最后一个元素
  3. 否则","分离每个元素
  4. 如果只有2个元素,那么它们应该打印为" xx和xx"
  5. 如果只有1个元素,则应打印为" xx"
  6. 所以这些字符串上面的字符串应该像这样打印:

    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
    

    但无法弄清楚如何实现我想要的输出。有人可以帮忙吗?

2 个答案:

答案 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"
相关问题