Tricky! To clarify, I think the problem is the following:
TravelPurpose should be “Work” IF
This seems like a good place to break out the old for
loop, as each iteration depends on values before and after it. There may be a more elegant vectorized solution, but this works:
# Load data and empty var1. Make sure to encode strings as characters, factors
# will mess up the logic below
df = read.csv("DRUGJul2.csv", stringsAsFactors=FALSE)
df$var1=character(11)
# Create vectors with the indices of anchor locations and travel activities
anchors = which(df$var2==1)
travels = which(df$var3=="Travel")
#Iterate through "travel" locations
for(i in travels) {
last_anchor = df$location[max(anchors[anchors < i])] #Get last anchor loc
next_anchor = df$location[min(anchors[anchors > i])] #Get next anchor loc
if("Office" %in% c(last_anchor, next_anchor)) { #Are either "Office"?
df$var1[i] = "Work"
}
}
You’ll get warnings if you have “Travel” values in the first and last rows but it should still work.
--
Check out our R resources at http://www.noamross.net/davis-r-users-group.html
---
You received this message because you are subscribed to the Google Groups "Davis R Users' Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to davis-rug+...@googlegroups.com.
Visit this group at http://groups.google.com/group/davis-rug.
For more options, visit https://groups.google.com/d/optout.