tanay
tanay

Reputation: 458

How to concatenate the results obtained in a loop using R

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)

What I am trying to do is in the function I am looping for 23 times and generating two values timer (contains values like T00, T01, T02...T23) and tempr (contains values like 23, 24, 25...). Now I want to store all the 23 respective values for the two variables in a dataframe so that my final output is

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

Upvotes: 0

Views: 1229

Answers (1)

Robert Krzyzanowski
Robert Krzyzanowski

Reputation: 9344

There are several lessons to be learned here. You can use seq(0,23) to construct the initial sequence, make a 1-row dataframe for each value, and use do.call with rbind to join them. You don't need paste or the if because you can use sprintf to add the 0's as needed. Finally, you don't need to use table on your grepl because which does the same thing and is more succinct.

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

If we are allowed to assume that x contains T00, T01, ..., T23 (every single one of them), then it becomes even shorter:

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

Upvotes: 1

Related Questions