选择唯一的非重复值

use*_*532 2 select r unique

我有一些2004 - 2007年的面板数据,我想根据独特的价值选择.更确切地说,我试图在整个期间找出各个商店的出入口.数据样本:

 store year    rev space  market
     1 2004 110000  1095     136
     1 2005 110000  1095     136
     1 2006 110000  1095     136
     1 2007 120000  1095     136
     2 2004  35000   800     136
     3 2004  45000  1000     136
     3 2005  45000  1000     136
     3 2006  45000  1000     136
     3 2007  45000  1000     136
     4 2005  17500   320     136
     4 2006  17500   320     136
     4 2007  17500   320     136
     5 2005  45000   580     191
     5 2006  45000   580     191
     5 2007  45000   580     191
     6 2004   7000   345     191
     6 2005   7000   345     191
     6 2006   7000   345     191
     7 2007  10000   500     191
Run Code Online (Sandbox Code Playgroud)

因此,例如我想知道在整个期间有多少商店退出市场,这应该是这样的:

 store year   rev space  market
     2 2004 35000   800     136
     6 2006  7000   345     191
Run Code Online (Sandbox Code Playgroud)

除了有多少商店进入市场,这意味着:

 store year    rev space  market
     4 2005  17500   320     136
     5 2005  45000   580     191
     7 2007  10000   500     191
Run Code Online (Sandbox Code Playgroud)

更新: 我没有包括它还应该承担现有的商店,例如:

 store year    rev  space  market
     1 2004 110000   1095     136
     1 2005 110000   1095     136
     1 2006 110000   1095     136
     1 2007 120000   1095     136     
     3 2004  45000   1000     136
     3 2005  45000   1000     136
     3 2006  45000   1000     136
     3 2007  45000   1000     136
Run Code Online (Sandbox Code Playgroud)

因为我是R的新手,所以即使在逐年的基础上,我一直在努力做到这一点.有什么建议?

Señ*_*r O 5

使用该data.table包,如果您data.frame被调用df:

dt = data.table(df)
exit = dt[,list(ExitYear = max(year)),by=store]
exit = exit[ExitYear != 2007] #Or whatever the "current year" is for this table

enter = dt[,list(EntryYear = min(year)),by=store]
enter = enter[EntryYear != 2003]
Run Code Online (Sandbox Code Playgroud)

UPDATE

要获取所有列而不仅仅是年份和商店,您可以执行以下操作:

exit = dt[,.SD[year == max(year)], by=store]
exit[year != 2007]
   store year   rev space market
1:     2 2004 35000   800    136
2:     6 2006  7000   345    191
Run Code Online (Sandbox Code Playgroud)