2016-12-16 69 views
2

我試圖產生降價的句子來處理動態數據結合for循環打印輸出中的R

###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),"%),")) 
} 

這裏是哪裏出了問題:

###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),"%),")) 
} 

我從一開始的輸出功能爲:

[1] 「鍵入ABC佔5(17%),」

[1]「B型佔爲8(28%),「

我不知道如何連接這些。

###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] 「C型佔7(24%),B型佔8(28%),C型佔7(24%)」。甲

+1

'PP < - 表(類型); pp < - 矩陣(c(名稱(pp),pp,round(prop.table(pp)* 100)),ncol = 3); (<%s佔%s(%s %%)',x [1],x [2],x [3])); sub('(。)','\\ U \\ 1',paste(pr,collapse =','),perl = TRUE)' – rawr

+0

pp < - table(Type); (c(名稱(pp),pp,round(prop.table(pp)* 100)),ncol = 3); (x,sprintf,'type%s佔%s(%s %%)',x [1],x [2],x [3])); pr < - paste0(sub('(。)','\\ U \\ 1',paste(pr,collapse =','),perl = TRUE),「。」) pr – SCDCE

回答

1
a <- as.character() 
for(i in 1:length(pt)) { 
    if(i ==1){ 
    a <- c(a, 
      paste0("Type ", 
        names(pt)[i], 
        " accounted for ", 
        t[i], 
        " (",round(pt[i]*100),"%),")) 
    } 
    if(i < length(pt) & i > 1){ 
    a <- c(a, 
          paste0("type ", 
          names(pt)[i], 
          " accounted for ", 
          t[i], 
          " (",round(pt[i]*100),"%),") 
) 
    } else if (i == length(pt)){ 
    a <- c(a, 
      paste0("type ", 
        names(pt)[i], 
        " accounted for ", 
        t[i], 
        " (",round(pt[i]*100),"%).") 
    ) 

    } 
} 

cat(a) 

類型佔9(31%),類型ABC佔5(17%),B型 佔8(28%),C型佔7(24%)。

如果您需要保存在一個對象setence這樣來做:

a <- capture.output(cat(a)) 
+0

if語句是隻是爲了處理句子不同部分的大小寫和標點符號。 –

+1

他們和我瞭解貓(),再次感謝! – SCDCE