0
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

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

2 Comments

X will be a value like "2008-08-13T23:04:10Z".... So I was using grepl to see if T00, T01...is present or not...
Your code is efficient and working but I have to make some minor changes before getting the desired result.. I have to write "Freq = table((grepl(timer, x)))["TRUE"]" in place of "Freq = which(grepl(timer, x))[1]"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.