2017-08-30 28 views
0

請考慮這個水果的例子一句:功能自動寫入給定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的使用?

+1

對於給定的例子,你的期望輸出是什麼? –

+0

嗨Ronak,我編輯了我的問題。我想輸入「價格(」korea「)」或任何一個國家,R會返回不超過平均成本的水果名稱。 –

+1

'colnames(fruit)[fruit [「korea」,]> colMeans(fruit)]'你想要的結果? – thelatemail

回答

1

我認爲你正在尋找的東西是這樣的:

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

嗯,我使用的嚴格更大的條件。如果你想要,你可以使用>=

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."