根据数据框中的值创建句子

时间:2017-08-18 00:43:46

标签: r

我想根据数据框中的值创建一个句子。我有以下data.frame:

canada <- c(50, 50, 50)
korea <- c(70, 70, 70)
brazil <- c(100, 100, 100)
fruit <- rbind(canada, korea, brazil)
colnames(fruit) <- c("apple", "orange", "banana")

fruit
>        apple orange banana
> canada    50     50     50
> korea     70     70     70
> brazil   100    100    100

当我输入加拿大时,希望输出看起来像这样:

canada
Canada consumes average number of apples, average number of oranges, 
and average number of bananas.

所以,我尝试了以下内容:

average <- 'average number of '
if(fruit$'apple' > 90)
{
  cat("Canada", 
          average, fruit$'apple', 
          average, fruit$'orange',
          "and ", average, fruit$'banana'
      )
}

当然,它不起作用,我被困在这里。有人能引导我走向正确的道路吗?我会投入工作学习!

2 个答案:

答案 0 :(得分:4)

这是我的尝试,假设你可能有除apple / orange / banana之外的列,但你总是想要给定行中的所有值。

myfun <- function(val){
  val <- tolower(val) # assuming all row names are in lower case
  myrow <- fruit[val,]

  phrase <- sapply(seq_along(myrow), 
                   function(x, n, i) {paste0("consumes average ", x[i], " of ", n[i], "s")}, # "s" added assuming there's always a plural number of fruits
                   x=myrow, n=names(myrow))
  phrase[length(phrase)] <- paste0("and ", phrase[length(phrase)], ".")
  phrase <- paste(phrase, collapse = ", ")

  cat(tools::toTitleCase(val), phrase)
}

> myfun("KOREA")
Korea consumes average 70 of apples, consumes average 70 of oranges, and consumes average 70 of bananas.
> myfun("canada")
Canada consumes average 50 of apples, consumes average 50 of oranges, and consumes average 50 of bananas.
> myfun("braZIL")
Brazil consumes average 100 of apples, consumes average 100 of oranges, and consumes average 100 of bananas.

答案 1 :(得分:1)

这样的东西?

canada <- c(50, 50, 50)
korea <- c(70, 70, 70)
brazil <- c(100, 100, 100)
fruit <- rbind(canada, korea, brazil)
colnames(fruit) <- c("apple", "orange", "banana")

CA<-fruit[1,1]
CO<-fruit[1,2]
CB<-fruit[1,3]

Canada<-paste("Canada on average eats",CA,"apples",CO,"oranges 
and",CB,"bananas")

>Canada
[1] "Canada on average eats 50 apples 50 oranges and 50 bananas"