我的数据框由个人和他们在某个时间点居住的城市组成。我想为每一年生成一个起点-终点矩阵,记录从一个城市到另一个城市的移动次数。我想知道:
- 如何在我的数据集中自动生成每年的起点-终点表?
- 如何以相同的 5x5 格式生成所有表格,在我的示例中,5 是城市的数量?
- 有没有比我在下面建议的更有效的代码?我打算在一个非常大的数据集上运行它。
考虑以下示例:
#An example dataframe
id=sample(1:5,50,T)
year=sample(2005:2010,50,T)
city=sample(paste(rep("City",5),1:5,sep=""),50,T)
df=as.data.frame(cbind(id,year,city),stringsAsFactors=F)
df$year=as.numeric(df$year)
df=df[order(df$id,df$year),]
rm(id,year,city)
我最好的尝试
#Creating variables
for(i in 1:length(df$id)){
df$origin[i]=df$city[i]
df$destination[i]=df$city[i+1]
df$move[i]=ifelse(df$orig[i]!=df$dest[i] & df$id[i]==df$id[i+1],1,0) #Checking whether a move has taken place and whether its the same person
df$year_move[i]=ceiling((df$year[i]+df$year[i+1])/2) #I consider that the person has moved exactly between the two dates at which its location was recorded
}
df=df[df$move!=0,c("origin","destination","year_move")]
为 2007 创建起点-终点表
yr07=df[df$year_move==2007,]
table(yr07$origin,yr07$destination)
结果
City1 City2 City3 City5
City1 0 0 1 2
City2 2 0 0 0
City5 1 1 0 0