I'm trying to generate a sentence in Markdown to handle dynamic data
###Generate some sample data
Type <- c("A","A","A","A","A","A","A","A","A",
"B","B","B","B","B","B","B","B",
"C","C","C","C","C","C","C",
"ABC","ABC","ABC","ABC","ABC")
Type <- as.data.frame(Type)
###Set the tables and iterations
l <- length(unique(Type$Type))
t <- table(as.character(Type$Type))
pt <- prop.table((table(as.character(Type$Type))))
###Loop to print the first type in sentence
for(i in seq(from=1, to=1)) {
typebegin <- print(paste0("Type ",
names(pt)[i],
" accounted for ",
t[i],
" (",round(pt[i]*100),"%),"))
}
Here's where the problem is:
###Loop to print all the types in the middle
for(i in seq(from=2, to=(l-1),by=1)) {
typemid <- print(paste0("type ",
names(pt)[i],
" accounted for ",
t[i],
" (",round(pt[i]*100),"%),"))
}
I get an output from the function as:
[1] "type ABC accounted for 5 (17%),"
[1] "type B accounted for 8 (28%),"
I don't know how to concatenate these.
###Loop to end the sentence
for(i in seq(from=l, to=l)) {
typeend <- print(paste0("type ",
names(pt)[i],
" accounted for ",
t[i],
" (",round(pt[i]*100),"%)."))
}
###Print the sentence
paste(typebegin, typemid, typeend)
[1] "Type C accounted for 7 (24%), type B accounted for 8 (28%), type C accounted for 7 (24%)."
pp <- table(Type); pp <- matrix(c(names(pp), pp, round(prop.table(pp) * 100)), ncol = 3); pr <- apply(pp, 1, function(x) sprintf('type %s accounted for %s (%s%%)', x[1], x[2], x[3])); sub('(.)', '\\U\\1', paste(pr, collapse = ', '), perl = TRUE)