这就是我所拥有的:
canada <- c(90, 50, 90)
korea <- c(60, 30, 90)
iran <- c(40, 20, 40)
fruit <- rbind(canada, korea, iran)
colnames(fruit) <- c("apple", "banana", "orange")
price <- function(val){
val <- tolower(val) # assuming all row names are in lower case
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))]
range <- c(paste0(nation, " has cheap fruit, ", score.min, " cents for one ", name.min, "."))
cat(range)
}
> price("iran")
Iran has cheap fruit, 20 cents for banana.
该脚本使用 which.min 来提供所选行的哪个单元格得分最低。
加拿大最便宜的水果是香蕉,价格为50美分,但仍然高于平均水平。我希望只有当香蕉的价格高于平均水平时才能打印计算机,产生如下句子:
> price("canada")
Canada's cheapest fruit is banana, but it is still more expensive than the average.
我总是可以手动输入列平均值并使用操作符号,但我希望是否有一个功能可以合并到我现在的功能中。
答案 0 :(得分:1)
这样的东西?
canada <- c(90, 50, 90)
korea <- c(60, 30, 90)
iran <- c(40, 20, 40)
fruit <- rbind(canada, korea, iran)
colnames(fruit) <- c("apple", "banana", "orange")
price <- function(val){
val <- tolower(val) # assuming all row names are in lower case
myrow <- fruit[val,]
nation <- tools::toTitleCase(val)
name.min <- names(myrow)[which.min(c(myrow))]
score.min <- c(myrow)[which.min(c(myrow))]
if (score.min < mean(fruit[, name.min])) {
cat(paste0(nation, "'s cheapest fruit is ", name.min,
", and it is cheaper than the average."))
} else {
cat(paste0(nation, "'s cheapest fruit is ", name.min,
", but it is still more expensive than the average."))
}
}
> price("iran") Iran's cheapest fruit is banana, and it is cheaper than the average. > price("canada") Canada's cheapest fruit is banana, but it is still more expensive than the average.