r - Creating a sentence based on the values in a data frame -
i want create sentence based on values in data frame. have 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 type canada, want output this:
canada canada consumes average number of apples, average number of oranges, , average number of bananas.
so, tried following:
average <- 'average number of ' if(fruit$'apple' > 90) { cat("canada", average, fruit$'apple', average, fruit$'orange', "and ", average, fruit$'banana' ) }
of course, doesn't work, , stuck here. can guide me right path? put in work learn!
here's attempt, assuming may have columns other apple / orange / banana, you'd want values in given row.
myfun <- function(val){ val <- tolower(val) # assuming row names 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 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, , consumes average 70 of bananas. > myfun("canada") canada consumes average 50 of apples, consumes average 50 of oranges, , consumes average 50 of bananas. > myfun("brazil") brazil consumes average 100 of apples, consumes average 100 of oranges, , consumes average 100 of bananas.
Comments
Post a Comment