在R

时间:2017-08-30 02:05:20

标签: r

请考虑这个果味的例子:

canada <- c(100, 80, 100, 100, 100, 100, 80, 100, 100)
korea <- c(100, 30, 100, 100, 100, 100, 30, 100, 100)
brazil <- c(100, 100, 100, 30, 100, 100, 100, 30, 100)
fruit <- rbind(canada, korea, brazil)
colnames(fruit) <- c("apple", "orange", "banana", "kiwi", "grape", "monkfruit", "strawberry", "melon", "pineapple")

并且,以下前提:

1)我不知道每列的平均价格。

2)我将每个水果价格与其平均值进行比较。

我想创建以下句子:

> price("korea")
> Every fruit costs above average except orange and strawberry.

所以,这是我到目前为止所尝试的:

price <- function(val){
  # General Functions ----
  val <- tolower(val)
  myrow <- fruit[val,]
  nation <- tools::toTitleCase(val)

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

  if (score.min < mean(fruit[, name.min])
      ) 
    cat("This is not exactly the right way to pull only the score that are below average because it only prints the minimum score.")
  } 

我可以使用快速命令来代替which.min吗?

2 个答案:

答案 0 :(得分:1)

如果您的主要目标是让R打印一句话,“在[国家/地区],除了[水果名称]之外,所有水果费用都高于平均水平”,那么请参阅下面的答案,其中打印出一个语法准确的句子,具体取决于载体的长度(例如果实数量)。

Canada <- c(100, 80, 100, 100, 100, 100, 80, 100, 100)
Korea <- c(100, 30, 100, 100, 100, 100, 30, 100, 100)
Brazil <- c(100, 100, 100, 30, 100, 100, 100, 30, 100)
fruit <- rbind(Canada, Korea, Brazil)
colnames(fruit) <- c("apple", "orange", "banana", "kiwi", "grape",    
                     "monkfruit", "strawberry", "melon", "pineapple")

price <- function(country,data){
  x <- names(which(!data[country,]>colMeans(data)))
  grammar <- function(x){
    setlength <- length(x)
    if(length(1:setlength)==1){
      setlist <- paste(x)
    } else {
      if(length(1:setlength)==2){
        setlist <- as.character(paste(x[1],"and",x[2]))
      } else {
        setlist <- as.character(paste0(
          paste(x[1:length(x)-1], collapse=", "),
                ", and ", x[length(x)])
        )
      }
    }
  }
  cat(paste0("In ",country,
               ", every fruit costs above average except ",
               grammar(x),"."))

price("Korea",fruit)

输出:

"In Korea, every fruit costs above average except apple, orange,   
banana, grape, monkfruit, strawberry, and pineapple."

答案 1 :(得分:1)

我认为你正在寻找这样的东西:

 price=function(val){
   cat("Every fruit costs above average except",
       names(which(!fruit[val,]>colMeans(fruit))))
  }

嗯,我使用了严格更大的条件。如果您愿意,可以使用>=