I am looking for swift way of reshaping the data from long to wide format. Right now I have tried a code with nest for loops, though the job gets done, it takes a long time to generate the output.
SN NN EE Service_tier
A B C economy
B C C economy
P Q R regular
Q S R regular
S R R regular
H I L economy
I J L economy
J K L economy
K L L economy
The output expected is as below
SN hop1 hop2 hop3 hop4 service_tier
A B C economy
P Q S R regular
H I J K L economy
currently the below code gets the job done. Am sure there is an effective and clean way to do this.
for (i in 1:lasrow){
sn <- raw_d[i,1]
nn <- raw_d[i,2]
en <- raw_d[i,3]
lc <- 1
if(nn == en){
d[lr,lc]<-sn
d[lr,lc+1]<-nn
d[lr,lc+2]<-en
lr <- lr+1
}
else{
while(nn!=en){
d[lr,lc]<-sn
lc <- lc+1
next_d <- filter(raw_d,raw_d$SN==sn,raw_d$EN==en)
if(dim(next_d)[1]==0){
d[lr,lc]<-"broken bf"
lc <- lc+1
break
}else{
sn <- next_d$NN
nn <- next_d$NN
}
}
d[lr,lc]<-en
lr<-lr+1
}
}