Q:

getting the first location where a person lived

I would like to create a first place column where a person lived based on the year column. I have the data in the following format
year<- c(2008, 2009, 2010, 2009, 2010, 2011)
person<- c('John', 'John', 'John', 'Brian', 'Brian','Vickey')
location<- c('London','Paris', 'Newyork','Paris','Paris','Miami')
df<- data.frame(year, person, location)

I would like to create a column called first place with values 0, 1. It is 1 if it is the first city else 0. 
Any suggestions?

A:

with data.tableyou can do:
library("data.table")
year<- c(2008, 2009, 2010, 2009, 2010, 2011)
person<- c('John', 'John', 'John', 'Brian', 'Brian','Vickey')
location<- c('London','Paris', 'Newyork','Paris','Paris','Miami')
df<- data.frame(year, person, location)
setDT(df)[, firstPlace:=as.integer(min(year)==year), person]
# > setDT(df)[, firstPlace:=as.integer(min(year)==year), person]
# > df
#    year person location firstPlace
# 1: 2008   John   London          1
# 2: 2009   John    Paris          0
# 3: 2010   John  Newyork          0
# 4: 2009  Brian    Paris          1
# 5: 2010  Brian    Paris          0
# 6: 2011 Vickey    Miami          1

or (as @Frank mentioned) if your data is sorted by person and year
setDT(df)[, firstPlace:=+!duplicated(person)]

or (a variant of this)
setDT(df)[, firstPlace:=+(rowidv(person)==1)]

A:

A solution with dplyr:
df %>% 
    group_by(person) %>% 
    mutate(FirstPlace = +(location[which.min(year)] == location))

# A tibble: 6 x 4
# Groups:   person [3]
#   year person location FirstPlace
#  <dbl> <fctr>   <fctr>      <int>
#1  2008   John   London          1
#2  2009   John    Paris          0
#3  2010   John  Newyork          0
#4  2009  Brian    Paris          1
#5  2010  Brian    Paris          1
#6  2011 Vickey    Miami          1

location[which.min(year)] to find out the first place, then compare the first place with location column and convert the boolean result to integer.

If only look at the first year:
df %>% 
    group_by(person) %>% 
    mutate(FirstPlace = +(min(year) == year))

# A tibble: 6 x 4
# Groups:   person [3]
#   year person location FirstPlace
#  <dbl> <fctr>   <fctr>      <int>
#1  2008   John   London          1
#2  2009   John    Paris          0
#3  2010   John  Newyork          0
#4  2009  Brian    Paris          1
#5  2010  Brian    Paris          0
#6  2011 Vickey    Miami          1

