如何使用R连接循环中获得的结果

时间:2014-03-25 23:44:59

标签: r function loops

myFunction <- function(x){
for(i in 0:23)
{
if(i<10){
  timer <- paste("T0",i, sep ="")
  tempr <- grepl(timer,x)
  tempr <- table(tempr)["TRUE"]
  timeCount <- c(timer,tempr) 
}
else{
  timer <- paste("T",i,sep="")
  tempr <- grepl(timer,x)
  tempr <- table(tempr)["TRUE"]
  timeCount <- c(timer,tempr) 
}
}
return(timeCount)
}
tmp <- myFunction(test$timestamp)

我要做的是在函数中我循环23次并生成两个值timer(包含值如T00,T01,T02 ... T23)和tempr(包含价值如23,24,25 ......)。现在我想在数据帧中存储两个变量的所有23个相应值,以便我的最终输出为

TimeZ Freq 
 T00   33
 T01   12
 T02   22
 T04   34
  .     .
  .     .
  .     .
 T23    23

1 个答案:

答案 0 :(得分:1)

这里有几个可以吸取的教训。您可以使用seq(0,23)构建初始序列,为每个值创建1行数据帧,并使用do.callrbind加入它们。您不需要pasteif,因为您可以根据需要使用sprintf添加0。最后,您不需要在table上使用grepl因为which执行相同的操作并且更简洁。

myFunction <- function(x) do.call(rbind, lapply(seq(0, 23), function(i)
  data.frame(TimeZ = timer <- sprintf("T%02d", i),
             Freq = which(grepl(timer, x))[1])
))

# example:
myFunction(sprintf("T%02d", sample(seq(0,23))))

#   TimeZ Freq
# 1   T00   14
# 2   T01   24
# 3   T02    2
# 4   T03    7
# 5   T04   19
# ----
#    TimeZ Freq
# 20   T19    9
# 21   T20   21
# 22   T21   22
# 23   T22   15
# 24   T23   13

如果我们被允许假设x包含T00T01,...,T23(每一个),那么它会变得更短:

 myFunction <- function(x) data.frame(TimeZ = sprintf("T%02d", seq(0, 23)),
                                      Freq = order(x))
相关问题