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.