How can I make a sentences that report values from each row in R? [duplicate]

耗尽温柔 提交于 2019-12-25 17:21:06

问题


Forgive me it's been a while. I'm writing a report and I want to generate sentences from this tree data "fill-in-the-blanks" style.

Here's some data for example:

species <- c("sugar maple","red oak","white ash","eastern hemlock")

size <- c(50,12,33,25)

condition <- c("fair","good","poor","good")

df <- data.frame(species, size, condition)

I'd like to get these sentences from the data:

- The sugar maple is 50 cm and is in fair condition
- The red oak is 12 cm and is in good condition
- The white ash is 33 cm and is in poor condition
- The eastern hemlock is 25 cm and is in good condition

So the data is filling in the blanks in "The ______ is __ cm and is in ____ condition"

I would like to be able to loop through different data sets and have a sentence for each tree (I think I'll be writing my first "for" loop).

If anyone could please direct me to a package or tutorial on how to do this I would be very grateful.

Thank you,

Jay


回答1:


You can use sprintf in base R

with(df, sprintf("The %s is %dcm and is in %s condition", species, size, condition))

#[1] "The sugar maple is 50cm and is in fair condition"    
#[2] "The red oak is 12cm and is in good condition"        
#[3] "The white ash is 33cm and is in poor condition"      
#[4] "The eastern hemlock is 25cm and is in good condition"

There is also glue package which does something similar

with(df, glue::glue("The {species} is {size}cm and is in {condition} condition"))


来源:https://stackoverflow.com/questions/59186300/how-can-i-make-a-sentences-that-report-values-from-each-row-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!