Jim O. Jim O. - 1 month ago 13
R Question

Creating a sentence based on the values in a data frame

I want to create a sentence based on the values in a data frame. I have the following 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


When I type canada, want the output to look like this:

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


So, I tried the following:

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


Of course, it doesn't work, and I am stuck here. Can someone guide me to the right path? I will put in the work to learn!

Answer Source

Here's my attempt, assuming that you may have columns other than apple / orange / banana, but you'd always want all the values in a given row.

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.