2016-12-15 65 views
1

降價報告句子如何生成這樣的句子:使用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

有一個更簡單的解決方案。只需在prop.table中包裝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%)......」

+0

那些「如何將這些數值插入到這些數據中: 」A型佔10%(34%),B型佔8%(28%),C型佔7%(24%), AB型爲5(17%)「。 – SCDCE

+0

@Seth剛剛更新了該效果的答案。 –

+0

是的,只是看如何顯示計數。謝謝。 – SCDCE