如果单词以s结尾,则单词末尾只有cat撇号(')

时间:2017-09-11 19:13:14

标签: r

假设以下果味示例:

canada <- c(48, 100, 56)
korea <- c(87, 79, 80)
laos <- c(20, 30, 10)
fruit <- rbind(canada, korea, laos)
colnames(fruit) <- c("apple", "orange", "banana")

> fruit
       apple orange banana
canada    48    100     56
korea     87     79     80
laos      20     30     10

我想添加一个占有式结构,所以我做了以下几点:

price <- function(val){

  val <- tolower(val)
  myrow <- fruit[val,]
  nation <- tools::toTitleCase(val)

  score.min <- c(myrow)[which.min(c(myrow))]
  name.min <- names(myrow)[which.min(c(myrow))]
  name.max <- names(which(myrow == max(myrow)))

  cat(paste0(nation, "'s ", name.min, "s typically cost ",  score.min, " cents per unit (USD).")
      )

}

其中,生成以下句子:

> price("laos")
Laos's bananas typically cost 10 cents per unit (USD).

我想要遵循美联社的新闻风格,并在撇号末端放弃 s ,只使用撇号(')来表示以结尾的单词>取值即可。一如既往,谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用gsub使用正面lookbehind。如果s后跟s',则以下内容仅会删除price <- function(val){ val <- tolower(val) myrow <- fruit[val,] nation <- tools::toTitleCase(val) score.min <- c(myrow)[which.min(c(myrow))] name.min <- names(myrow)[which.min(c(myrow))] name.max <- names(which(myrow == max(myrow))) string = paste0(nation, "'s ", name.min, "s typically cost ", score.min, " cents per unit (USD).") string = gsub("(?<=s')s", "", string, perl = TRUE) cat(string) } price("laos") # Laos' bananas typically cost 10 cents per unit (USD).

git stash
git pull origin master

答案 1 :(得分:1)

编写一个处理所有格的函数,然后在price中调用它:

possessive <- function(x) {
  ifelse(
    endsWith(x, "s"),
    paste0(x, "'"),
    paste0(x, "'s")
  )
}

price <- function(val){

  val <- tolower(val)
  myrow <- fruit[val,]
  nation <- tools::toTitleCase(val)

  score.min <- c(myrow)[which.min(c(myrow))]
  name.min <- names(myrow)[which.min(c(myrow))]
  name.max <- names(which(myrow == max(myrow)))

  cat(paste0(possessive(nation), " ", name.min, "s typically cost ",  score.min, " cents per unit (USD).")
  )

}