0

Based on a condition in the column geodf$def of the dataframe geodf where the values are 0,1:4 and there are no NA, I want to extract time values either from the column geodf$time or from the column geodf$time.stop. Both time columns are in the format "%Y%m%d %H%M%S".

I tried to solve the problem both with a chain of ifelse statements and with a for loop, but in both cases I got results in a numeric format (like "1433310096") which I am not able to reconvert on the original format "%Y%m%d %H%M%S".

Here the first attempt with the chain of ifelse statements:

geodf$start.stop<-ifelse(geodf$def==1,geodf$time,
                              ifelse(geodf$def==2,geodf[row(as.matrix(geodf$time))-1],"time"],
                                     ifelse(geodf$def==3,geodf$time.stop,0)))

And here the second attempt with the for loop

geodf$start.stop<-0
for (i in 1:length(geodf$time)){
  if(geodf[i,"def"]==1){
    geodf[i,"start.stop"]<-as.Date(geodf[i,"time"], format="%Y%m%d %H%M%S")
  } else if (geodf[i,"def"]==2){
    geodf[i,"start.stop"]<-as.Date(geodf[i-1,"time"], format="%Y%m%d %H%M%S")
  } else if (geodf[i,"def"]==3){
    geodf[i,"start.stop"]<-as.Date(geodf[i-1,"time.stop"], format="%Y%m%d %H%M%S")}}

Furthermore, considered the large size of my dataset, the for loop needs lots of time.

I hope someone can help me.

Element
  • 1
  • 2
  • You should add some data to the question, your times are converted to numbers somewhere but not knowing the types of the different columns it is hard to tell where. See http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610 for adding the data. – kasterma Jul 21 '15 at 14:28
  • BTW: `as.POSIXct(1433310096, origin="1970-01-01")` gives `"2015-06-03 07:41:36 CEST"`. May help for converting back if you can't avoid the coercion in the first place. – kasterma Jul 21 '15 at 14:32
  • do `str(geodf)` and give us the result. – Dean MacGregor Jul 21 '15 at 15:15
  • Ok, with `as.POSIXct(1433310096, origin="1970-01-01")` works fine. Thank you all – Element Jul 22 '15 at 15:07

0 Answers0