使用lapply从动态数据生成Markdown报告的句子

时间:2016-12-15 20:17:43

标签: r function r-markdown lapply

如何生成这样的句子:

Type A accounted for 10 (34%), type B for 8 (28%), and type C for 7 (24%), and type AB for 5 (17%).

来自这样的动态数据:

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",
           "AB","AB","AB","AB","AB")
Type <- as.data.frame(Type)

我不熟悉应用于从唯一变量生成的列表的lapply函数,但我有点不知道这个。

library(dplyr)

Type_list <- function(data, type) {

  data %>% 
  filter(Type == type) %>% 
  paste(type, length(Type$Type[Type$Type == x])) %>%
  paste0(((length(Type$Type[Type$Type == x]))/length(Type$Type)*100), "%")

}

i <- unique(Type$Type)

lapply(i, function(x) Type_list(Type, x))

if语句会比lapply好吗?

1 个答案:

答案 0 :(得分:1)

有一个更简单的解决方案。只需在table中包含prop.table语句即可。这就是它的意思。

prop.table(table(Type))
Type
        A        AB         B         C 
0.3103448 0.1724138 0.2758621 0.2413793
table(Type)
Type
 A AB  B  C 
 9  5  8  7

然后你的句子:

pt <- prop.table(table(Type))

t  <- table(Type)


paste0("Type ", names(pt)[1], " accounted for ", t[1], " (",pt[1]*100,"%)...")
  

[1]“A型占9(31.0344827586207%)......”

等等。顺便说一句,你可以根据需要对数字进行舍入,如round(pt[1]*100),即

paste0("Type ", names(pt)[1], " accounted for ", t[1], " (",round(pt[1]*100),"%)...")
  

[1]“A型占9(31%)......”