2016-12-16 68 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