在R中组合循环打印输出

时间:2016-12-16 16:06:59

标签: r for-loop

我试图在Markdown中生成句子来处理动态数据

###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]&#34; ABC类型占5(17%),&#34;

[1]&#34; B型占8(28%),&#34;

我不知道如何连接它们。

###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]&#34; C型占7(24%),B型占8(28%),C型占7(24%)。&#34;

1 个答案:

答案 0 :(得分: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)
  

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

如果您需要将对象保存在对象中,请执行以下操作:

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